How to set color of templated image in NSTextAttachment

后端 未结 7 1053
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 20:30

How can I set the color of a templated image that is an attachment on an attributed string?

Background:

I\'ve got a UILabel and I\'m setting its attributedTe

相关标签:
7条回答
  • 2020-12-29 21:09

    On iOS 12 we'll need to insert a character before the image and set the foreground color on that character. However, on iOS 13 we can set the foreground color directly on the NSAttributedString that contains our NSTextAttachment.

    I have tested the following extension on iOS 12.3 and iOS 13.3.1

    extension NSMutableAttributedString {
        @discardableResult
        func sbs_append(_ image: UIImage, color: UIColor? = nil) -> Self {
            let attachment = NSTextAttachment()
            attachment.image = image
            let attachmentString = NSAttributedString(attachment: attachment)
            if let color = color {
                if #available(iOS 13, *) {} else {
                    // On iOS 12 we need to add a character with a foreground color before the image,
                    // in order for the image to get a color.
                    let colorString = NSMutableAttributedString(string: "\0")
                    colorString.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: colorString.length))
                    append(colorString)
                }
                let attributedString = NSMutableAttributedString(attributedString: attachmentString)
                if #available(iOS 13, *) {
                    // On iOS 13 we can set the foreground color of the image.
                    attributedString.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: attributedString.length))
                }
                append(attributedString)
            } else {
                append(attachmentString)
            }
            return self
        }
    }
    
    0 讨论(0)
提交回复
热议问题