如何在标签中添加两个NSTextAttachment?
我想在我的标签中添加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
它运作良好。