【问题标题】:How do you add an image attachment to an AttributedString?如何向 AttributedString 添加图像附件?
【发布时间】:2023-02-21 02:58:09
【问题描述】:

我正在努力将 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】:

    NSAttributedString(attachment:) 神奇地创建了一个带有单个字符的 NSAttributedStringNSAttachmentCharacter 是 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)
    }()
    

    【讨论】:

      猜你喜欢
      • 2021-10-03
      • 2021-12-28
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多