UITextView设置前景色后NSTextAttachment图片显示异常求助
问题分析与解决方案
我之前在iOS 13 + Xcode 11的环境下也踩过这个坑!你遇到的情况其实是iOS系统处理富文本属性继承时的一个非预期行为(算不上严格意义上的Bug,但确实和我们的直觉不符):当你给整个NSMutableAttributedString设置了.foregroundColor属性后,后续追加的NSTextAttachment对应的属性字符串会继承这个颜色属性,系统会用这个颜色作为图片的蒙版进行渲染,导致图片看起来是空白的。
为什么你单独移除图片区域的前景色无效?
大概率是你移除属性时的range设置有误——NSTextAttachment对应的属性字符串长度是1,所以必须确保移除操作的range是NSRange(location: 0, length: 1),否则不会生效。
解决方案(两种可选)
方案1:给图片属性字符串单独清除前景色
在追加图片字符串前,显式移除它的.foregroundColor属性,阻止它继承父字符串的颜色:
let attrString = NSMutableAttributedString(string: rawText, attributes: [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.black]) let attachment = NSTextAttachment(image: image) let imgStr = NSMutableAttributedString(attachment: attachment) // 关键:清除图片字符串的前景色属性 imgStr.removeAttribute(.foregroundColor, range: NSRange(location: 0, length: imgStr.length)) attrString.append(imgStr) textview.attributedText = attrString
方案2:仅给文本部分设置前景色
先创建只包含字体属性的基础字符串,再单独给文本区域设置前景色,最后追加图片字符串(图片区域不会被设置颜色):
let attrString = NSMutableAttributedString(string: rawText, attributes: [.font: UIFont.systemFont(ofSize: 17)]) // 仅给原始文本部分设置前景色 attrString.addAttribute(.foregroundColor, value: UIColor.black, range: NSRange(location: 0, length: rawText.count)) let attachment = NSTextAttachment(image: image) let imgStr = NSMutableAttributedString(attachment: attachment) attrString.append(imgStr) textview.attributedText = attrString
这两种方法都能完美解决你的问题:既保留了文本的黑色,又能正常显示图片。
内容的提问来源于stack exchange,提问作者Fried Rice
相关产品推荐
相关产品推荐

