繁体   English   中英

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

[英]How to add two NSTextAttachment in a label?

我想在标签中添加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

这是@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

我在评论中关注了@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 

它运作良好。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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