swift - NSAttributedString 无法从 DTCoreText 解析 CTForegroundColor 属性

标签 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 = "[ (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; 扩展范围)] ( 0.921569 0.113725 0.113725 1 )"; NSFont = "font-family:\"Helvetica\"; font-weight: normal; font-style: normal; font-size: 22.00pt"; NSParagraphStyle = "{基本书写方向=-1,对齐=4,换行方式=0,默认tab间隔=36\n首行首缩=0,首缩=0,尾缩=0\n行高倍数=0,最大行高=0,最小行高=0\n行间距调整=0,段落间距=0,段落前间距=0\n}";

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

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

输出属性字符串:

立即赚钱!{ NSColor = "kCGColorSpaceModelRGB 0.921569 0.113725 0.113725 1 "; NSFont = "font-family:\"Helvetica\"; font-weight: normal; font-style: normal; font-size: 22.00pt"; NSKern = 0; NSParagraphStyle = "Alignment 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"; NSStrokeColor = "kCGColorSpaceModelRGB 0.921569 0.113725 0.113725 1 "; NSStrokeWidth = 0;

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

最佳答案

将以下代码添加到选项参数有效!!

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

原因是将上述属性设置为 true 使用 NSForegroundColorAttributeName(仅适用于 iOS 6.0 及更高版本)而不是默认的 kCTForegroundColorAttributeName。

关于swift - NSAttributedString 无法从 DTCoreText 解析 CTForegroundColor 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48844782/

相关文章:

swift - UIlabel切换粗体

ios - 发送消息动画像iMessage发送消息使用UICollectionView自定义

iOS - IB 中的 UILabel attributedText 无法更改字体大小

ios - DTCoreText 图像不显示

ios - 执行后的 DTCoreText 错误消息

swift - 如何在 Swift 3 的 DTCoreText 中显示与 html 内联的图像

swift - 如何重新创建这种效果,即 UIcollectionview 单元格在点击顶部时转到背景

ios - 委托(delegate)协议(protocol)的实现方法在哪里调用?

ios - 获取属性字符串中具有 url 属性的字符串数量

objective-c - NSTextField 添加行间距