如何向 AttributedString 添加图像附件?

问题描述 投票:0回答:1

我正在努力将

NSAttributedString
替换为
AttributedString
但未能成功使附件工作。尽管我应用了附件,但图像并未出现在字符串中。

let textAttachment = NSTextAttachment(image: UIImage(systemName: "exclamationmark.triangle.fill")!)
textAttachment.accessibilityLabel = "Warning"

// Original code
label.attributedText = NSAttributedString(attachment: textAttachment)

// New code
var attributedString = AttributedString()
attributedString.attachment = textAttachment
label.attributedText = NSAttributedString(attributedString)
ios nsattributedstring ios15 attributedstring
1个回答
0
投票

NSAttributedString(attachment:)
神奇地创建了一个带有单个字符的
NSAttributedString
NSAttachmentCharacter
是 U+FFFC 对象替换字符)并应用文本附件属性以用图像替换该字符。

使用新的

AttributedString
API,您需要手动复制:

let textAttachment = NSTextAttachment(image: UIImage(systemName: "exclamationmark.triangle.fill")!)
textAttachment.accessibilityLabel = "Warning"

let attributedString = AttributedString("\(UnicodeScalar(NSTextAttachment.character)!)", attributes: AttributeContainer.attachment(textAttachment))

label.attributedText = NSAttributedString(attributedString)

这是一个用图像替换子字符串的例子:

let addString = "+"
let string = "Tap \(addString) to add a task."
let addTextAttachment = NSTextAttachment(image: UIImage(systemName: "plus.square")!)

// NSAttributedString
label.attributedText = {
    let attributedString = NSMutableAttributedString(string: string)
    attributedString.replaceCharacters(in: (attributedString.string as NSString).range(of: addString), with: NSAttributedString(attachment: addTextAttachment))
    return attributedString
}()

// AttributedString
label.attributedText = {
    var attributedString = AttributedString(string)
    let attachmentString = AttributedString("\(UnicodeScalar(NSTextAttachment.character)!)", attributes: AttributeContainer.attachment(addTextAttachment))
    attributedString.replaceSubrange(attributedString.range(of: addString)!, with: attachmentString)
    return NSAttributedString(attributedString)
}()
© www.soinside.com 2019 - 2024. All rights reserved.