簡體   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