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.
source to share