如何将图像附件添加到 AttributedString 中?

Jor*_*n H 4 nsattributedstring ios swift ios15 attributedstring

我正在努力替换NSAttributedStringAttributedString但未能成功使附件正常工作。尽管我应用了附件,但图像并未出现在字符串中。

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)
Run Code Online (Sandbox Code Playgroud)

Jor*_*n H 5

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

使用新的AttributedStringAPI,您需要手动复制:

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)
Run Code Online (Sandbox Code Playgroud)

下面是用图像替换子字符串的示例:

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)
}()
Run Code Online (Sandbox Code Playgroud)