设置属性后,NSTextAttachment图像消失 [英] NSTextAttachment Image Disappears When Attributes Are Set
问题描述
我无法将属性应用于 NSMutableAttributedString
s。如果它们具有图像附件,则在添加属性时图像就会消失。
I'm having trouble applying attributes to NSMutableAttributedString
s. If they have an image attachment, the image goes away when the attributes get added.
采用 NSMutableAttributedString
文本附件,例如:
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))
现在该字符串以正确的字体显示,但附件不见了。如果我将范围设置为 myString.length-1
,附件将继续存在,因此我可能需要做更多的工作才能遍历所有附件(也许通过查找 NSTextAttachmentCharacter
)。我想知道是否缺少更简单的东西。
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.
推荐答案
解决方案是不使用 setAttributes:
但 addAttributes:
,因为它会重置最初在字符串上设置的属性。从文本附件生成属性字符串时,它会设置显示图像所需的一些初始属性。
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.
这篇关于设置属性后,NSTextAttachment图像消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!