swift - 具有前景色的属性文本中的 NSTextAttachment 图像

标签 swift nsattributedstring nstextattachment

当我将图像附件添加到具有前景色集的 UITextView 时,图像会被设置的颜色遮挡:

enter image description here

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

当我删除 .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

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

最佳答案

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

let attachment = NSTextAttachment()
attachment.image = image

关于swift - 具有前景色的属性文本中的 NSTextAttachment 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58153505/

相关文章:

objective-c - 带有附件的 NSAttributedString 的 NSTextField 的奇怪行为

ios - 嵌入 NSTextAttachment 时高 UILabel 中缺少的行

ios - UITextView 中的视频

swift - 计算 NSSound 循环的次数(Swift)

ios - 创建一个具有相同高度的静态单元格的 View 表以填充屏幕

ios - 为什么我的函数在 Swift 中无法正确自动完成?

ios - 在 NSTextStorage 范围内崩溃

cocoa - NSUnderlineStyle Single 是两个像素

ios - 如何在 rtf 文件中写入 NSAttributedString?

ios - 如何调整属性字符串中符号图像的大小