How do I add two NSTextAttachment shortcuts to a label?
I want to add 2 icons to my label. I have 2 images, one is a bird and one is a duck.
I want my label to display text like this:
[Bird Image] Bird [Duck Image] Duck.
Currently, I just know what is on it NSTextAttachment
.
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
to the label.
-1
source to share
2 answers
Here's a little tweak by @Khuong and @Larme is responsible for brevity:
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
+2
source to share
I followed @Larme in a 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
Works well.
0
source to share