swift 如何向AttributedString添加图像附件?

qacovj5a  于 2023-02-21  发布在  Swift
关注(0)|答案(1)|浏览(167)

我正在尝试用AttributedString替换NSAttributedString,但是没有成功地使附件生效。尽管我应用了附件,但是图像没有出现在字符串中。

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)
n3schb8v

n3schb8v1#

NSAttributedString(attachment:)神奇地创建了一个包含单个字符的NSAttributedStringNSAttachmentCharacter是U+FFFC OBJECT REPLACEMENT CHARACTER),并应用了text attachment属性,以便用图像替换该字符。
使用新的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)
}()

相关问题