Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextAttachment Image Disappears When Attributes Are Set

I'm having trouble applying attributes to NSMutableAttributedStrings. 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.

like image 607
davextreme Avatar asked Oct 15 '14 20:10

davextreme


1 Answers

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.

like image 200
Josh Bernfeld Avatar answered Oct 22 '22 06:10

Josh Bernfeld