如何在标签中添加两个NSTextAttachment?

时间:2016-06-24 15:03:27

标签: ios swift

我想在我的标签中添加2个图标。我有2张图片:一张是鸟,一张是鸭子。

我希望我的标签显示如下文字:

[鸟图像]鸟[鸭子图像]鸭子。

目前,我只知道在标签中实现一个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

那么如何在标签中添加2 NSTextAttachment

2 个答案:

答案 0 :(得分:2)

以下是@Khuong和@ Larme对简洁性的回答:

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

答案 1 :(得分:0)

我在评论中跟随@Larme回答。

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 

效果很好。

enter image description here