DTCoreText生成的NSAttributedString的CTForegroundColor属性解析异常,UI显示颜色不符
解决DTCoreText生成的NSAttributedString颜色显示异常问题
我之前也踩过DTCoreText这个颜色显示的坑!问题根源其实很清楚:
DTCoreText是基于CoreText框架实现的,它给生成的富文本添加的是**CoreText专属的kCTForegroundColorAttributeName(也就是你看到的CTForegroundColor)属性来存储文本颜色;但咱们常用的UIKit组件(比如UILabel、UITextView)默认只识别UIKit的NSForegroundColorAttributeName**属性,对CoreText的属性不买账,所以就会出现属性里明明有颜色,但显示不对的情况。而苹果标准方法生成的富文本,用的都是UIKit的属性,自然能正常显示。
给你两个可行的解决办法:
办法一:转换属性,让UIKit能识别
拿到DTCoreText返回的富文本后,遍历所有字符范围,把CTForegroundColor对应的CGColor转成UIColor,再赋值给UIKit的颜色属性:
// 假设dtAttributedString是DTCoreText生成的富文本 NSAttributedString *dtAttributedString = [DTHTMLAttributedStringBuilder attributedStringWithHTML:...]; NSMutableAttributedString *mutableAttrString = [dtAttributedString mutableCopy]; // 遍历所有属性范围 [mutableAttrString enumerateAttributesInRange:NSMakeRange(0, mutableAttrString.length) options:0 usingBlock:^(NSDictionary<NSAttributedStringKey,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) { // 获取CoreText的颜色属性 CGColorRef ctColor = attrs[(id)kCTForegroundColorAttributeName]; if (ctColor) { // 转成UIKit的UIColor UIColor *uiColor = [UIColor colorWithCGColor:ctColor]; // 设置UIKit识别的颜色属性 [mutableAttrString addAttribute:NSForegroundColorAttributeName value:uiColor range:range]; // 可选:移除CoreText的颜色属性,减少冗余 // [mutableAttrString removeAttribute:(id)kCTForegroundColorAttributeName range:range]; } }]; // 之后用mutableAttrString给UILabel/UITextView赋值即可 yourLabel.attributedText = mutableAttrString;
办法二:直接使用DTCoreText的专属显示组件
DTCoreText本身提供了适配CoreText属性的显示控件,比如DTAttributedLabel,它是基于CoreText渲染的,能直接识别CTForegroundColor属性,不用做任何转换:
// 创建DTAttributedLabel DTAttributedLabel *dtLabel = [[DTAttributedLabel alloc] initWithFrame:CGRectMake(20, 20, 300, 100)]; // 直接赋值DTCoreText生成的富文本 dtLabel.attributedString = dtAttributedString; // 添加到视图 [self.view addSubview:dtLabel];
这样就能完美显示正确的颜色了,两种办法选哪种看你的场景:如果已经在用UIKit的控件,选办法一;如果项目里本来就大量用DTCoreText的组件,办法二更省心。
内容的提问来源于stack exchange,提问作者atul
相关产品推荐
相关产品推荐

