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
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
}
}