NSAttributedString无法解析DTCoreText

时间:2018-02-17 18:51:26

标签: swift nsattributedstring dtcoretext

我正在使用DTCoreText来创建HTML属性字符串。 DTCoreText返回的属性字符串有一个名为" CTForegroundColor"它有文字颜色信息。当我在UI上显示文本时,它不是按照属性中提到的颜色。如果我使用苹果公司的标准方法,那么它可以正常工作。

代码段:

1。使用DTCoreText时

let stringBuilder : DTHTMLAttributedStringBuilder  = DTHTMLAttributedStringBuilder.init(html: encodedData, options: nil, documentAttributes: nil)

return stringBuilder.generatedAttributedString()!

输入字符串:

"<style>body{font-family: \'Helvetica\'; font-size:22.000000px;}</style><font color = \"#EB1D1D\">Earn Instantly!</font>"

输出属性字符串:

立即赚取! {      CTForegroundColor =&#34; [(kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1;扩展范围)](0.921569 0.113725 0.113725 1)&#34 ;;     NSFont =&#34; font-family:\&#34; Helvetica \&#34 ;; font-weight:normal; font-style:normal; font-size:22.00pt&#34 ;;     NSParagraphStyle =&#34; {base writing direction = -1,alignment = 4,line break mode = 0,default tab interval = 36 \ n first line head indent = 0,head indent = 0,tail indent = 0 \ nline height multiple = 0,最大行高= 0,最小行高= 0 \ n行间距调整= 0,段间距= 0,段间距= 0 \ n}&#34 ;; }

2。使用Apple的标准方法时:

return try NSAttributedString(data: encodedData,
                                              options: [.documentType: NSAttributedString.DocumentType.html,
                                                        .characterEncoding: String.Encoding.utf8.rawValue],
                                              documentAttributes: nil)

输出属性字符串:

立即赚取! {      NSColor =&#34; kCGColorSpaceModelRGB 0.921569 0.113725 0.113725 1&#34 ;;     NSFont =&#34; font-family:\&#34; Helvetica \&#34 ;; font-weight:normal; font-style:normal; font-size:22.00pt&#34 ;;     NSKern = 0;     NSParagraphStyle =&#34;对齐4,LineSpacing 0,ParagraphSpacing 0,ParagraphSpacingBefore 0,HeadIndent 0,TailIndent 0,FirstLineHeadIndent 0,LineHeight 27/0,LineHeightMultiple 0,LineBreakMode 0,Tabs(\ n),DefaultTabInterval 36,Blocks(\ n),列表(\ n),BaseWritingDirection 0,HyphenationFactor 0,TighteningForTruncation NO,HeaderLevel 0&#34 ;;     NSStrokeColor =&#34; kCGColorSpaceModelRGB 0.921569 0.113725 0.113725 1&#34 ;;     NSStrokeWidth = 0; }

由于我在使用Apple的标准方法时遇到太多崩溃,所以我想转移到DTCoreText。

1 个答案:

答案 0 :(得分:1)

将以下代码添加到options参数中!!

let options = [DTUseiOS6Attributes : true] as [String : Any]

原因是将上面的属性设置为true会使用NSForegroundColorAttributeName(仅适用于iOS 6.0)而不是默认的kCTForegroundColorAttributeName。