NSTextAttachment image disappears when setting attributes

I am having trouble applying attributes to NSMutableAttributedString

s. If they have an image attachment, the image disappears when attributes are added.

Take NSMutableAttributedString

one that includes a text attachment like:

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 the attribute to a string, I lose the nesting:

let bodyFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
myString.setAttributes([NSFontAttributeName: bodyFont], 
                       range: NSMakeRange(0, myString.length))

      

The line is now displayed in the correct font, but the attachment is missing. If I do the range myString.length - 1

, the application is still valid, so I could probably stagger any attachments with a little work (perhaps choosing NSTextAttachmentCharacter

). I am wondering if something simpler I am missing.

+3


source to share


1 answer


The solution for this is to not use setAttributes: but addAttributes: because it resets the attributes that were originally set on the string. When you create an attributed string from a text attachment, some initial attributes are set that are required to display the image.



+3


source







All Articles