I'm having trouble applying attributes to NSMutableAttributedString
s. If they have an image attachment, the image goes away when the attributes get added.
Take an NSMutableAttributedString
that includes a text attachment, like this:
let myString = NSMutableAttributedString(string: "Hello\n\n")
let attachment = NSTextAttachment()
attachment.image = image // some UIImage
let attachmentString = NSAttributedString(attachment: attachment)
myString.appendAttributedString(attachmentString)
If I try to apply an attribute to the string, I lose the attachment:
let bodyFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
myString.setAttributes([NSFontAttributeName: bodyFont],
range: NSMakeRange(0, myString.length))
The string now appears with the right font but the attachment is gone. If I make the range myString.length - 1
the attachment persists so I could probably step around any attachments with a little more work (maybe by looking for NSTextAttachmentCharacter
). I'm wondering if there's something simpler I'm missing.
The solution for this is to not use setAttributes:
but addAttributes:
because it resets attributes that are set on the string initially. When generating an attributed string from a text attachment it sets some initial attributes that are needed to display the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With