简体   繁体   中英

How to add two NSTextAttachment in a label?

I want to add 2 icons in my label. I have 2 images: one is bird and one is duck.

I want my label to show a text like this:

[Bird Image] Bird [Duck Image] Duck.

Currently, I just know implement one NSTextAttachment in a label.

let birdAttachment = NSTextAttachment()
let birdImage = UIImage(named:"bird")
birdAttachment.image = birdImage
let birdString = NSMutableAttributedString(string: "Bird")
let stringWithBirdImage = NSMutableAttributedString(attributedString: NSAttributedString(attachment: birdAttachment))
stringWithBirdImage.appendAttributedString(birdString)

let duckAttachment = NSTextAttachment()
let duckImage = UIImage(named: "duck")
duckAttachment.image = duckImage
let duckString = NSMutableAttributedString(string: "Duck")
let stringWithDuckImage = NSMutableAttributedString(attributedString: NSAttributedString(attachment: duckAttachment))
stringWithDuckImage.appendAttributedString(duckString)
label.attributedText = stringWithBirdImage

So how to add 2 NSTextAttachment in a label.

Here's a small tweak to @Khuong and @Larme's answer for conciseness:

func stringForAttachment(named imageName: String, caption: String) -> NSAttributedString {
    let attachment = NSTextAttachment()
    let image = UIImage(named: imageName)
    attachment.image = image
    let fullString = NSMutableAttributedString(string: caption)
    fullString.appendAttributedString(NSAttributedString(attachment: attachment))
    return fullString
}

let labelText = NSMutableAttributedString()
labelText.appendAttributedString(stringForAttachment(named: "bird", caption: "Bird"))
labelText.appendAttributedString(stringForAttachment(named: "duck", caption: "Duck"))
label.attributedText = labelText

I followed @Larme answer in the comment.

let birdAttachment = NSTextAttachment()
let birdImage = UIImage(named:"bird")
birdAttachment.image = birdImage
let birdString = NSAttributedString(string: "Bird")
let stringWithBirdImage = NSAttributedString(attributedString: NSAttributedString(attachment: birdAttachment))

let duckAttachment = NSTextAttachment()
let duckImage = UIImage(named: "duck")
duckAttachment.image = duckImage
let duckString = NSAttributedString(string: "Duck")
let stringWithDuckImage = NSAttributedString(attributedString: NSAttributedString(attachment: duckAttachment))

let finalAttributedString = NSMutableAttributedString(string: "")
finalAttributedString.appendAttributedString(stringWithBirdImage)
finalAttributedString.appendAttributedString(birdString)
finalAttributedString.appendAttributedString(stringWithDuckImage)
finalAttributedString.appendAttributedString(duckString)
label.attributedText = finalAttributedString 

It works well.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM