带有前景色的属性文本中的 NSTextAttachment 图像

Fri*_*ice 2 nsattributedstring nstextattachment swift

当我将图像附件添加到带有前景色设置的 UITextView 时,图像会被设置的颜色消隐:

在此处输入图片说明

let attrString = NSMutableAttributedString(string: rawText, attributes: [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.black])
let attachment = NSTextAttachment(image: image)
let imgStr = NSMutableAttributedString(attachment: attachment)
attrString.append(imgStr)
textview.attributedText = attrString
Run Code Online (Sandbox Code Playgroud)

当我删除 时.foregroundColor: UIColor.black,图像显示正确,但我需要能够设置属性文本颜色。

我试图.foregroundColor在添加图像附件后明确删除该属性,但没有运气。我还尝试.foregroundColor从大部分文本中删除该属性,但它仍然不起作用,只能从整个字符串中删除该属性:

attrString.removeAttribute(.foregroundColor, range: NSRange(location: attrString.length-1, length: 1)) // does not work
// -------
attrString.removeAttribute(.foregroundColor, range: NSRange(location: 1, length: attrString.length-1)) // does not work
// -------
attrString.removeAttribute(.foregroundColor, range: NSRange(location: 0, length: attrString.length)) // works but no text colour
Run Code Online (Sandbox Code Playgroud)

这是在 Xcode 11.0、iOS 13 上开发的。这是 UITextView/iOS 错误还是预期行为(我认为不太可能)?如何使用文本颜色集正确显示图像?

Fri*_*ice 11

看起来NSTextAttachment(image:)构造函数存在错误(在 iOS 13 上,在此回答时),以下图像附件构造正常工作:

let attachment = NSTextAttachment()
attachment.image = image
Run Code Online (Sandbox Code Playgroud)

  • 真是救星啊!我将此作为错误提交:FB7361120 (2认同)