设置属性时,NSTextAttachment图像消失

dav*_*eme 5 cocoa-touch swift

我在将属性应用于NSMutableAttributedStrings时遇到问题.如果他们有图像附件,则在添加属性时图像会消失.

拿一个NSMutableAttributedString包含文本附件的内容,如下所示:

let myString = NSMutableAttributedString(string: "Hello\n\n")
let attachment = NSTextAttachment()
attachment.image = image    // some UIImage
let attachmentString = NSAttributedString(attachment: attachment)
myString.appendAttributedString(attachmentString)
Run Code Online (Sandbox Code Playgroud)

如果我尝试将属性应用于字符串,则会丢失附件:

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

字符串现在显示为正确的字体但附件已消失.如果我制作范围myString.length - 1附件仍然存在,那么我可以用更多的工作(可能通过寻找NSTextAttachmentCharacter)踩到任何附件.我想知道是否有更简单的东西我不知道.

Jos*_*eld 7

解决方案是不使用setAttributes:而是addAttributes:因为它会重置最初在字符串上设置的属性.从文本附件生成属性字符串时,它会设置显示图像所需的一些初始属性.