Search code examples
swiftnsattributedstringdtcoretext

NSAttributedString can not parse CTForegroundColor attribute from DTCoreText


I am using DTCoreText to create HTML attributed string. the attributed string returned by DTCoreText has one attribute named "CTForegroundColor" which has text color information. When I display the text on UI it is not as per the color mentioned in the attribute. If I use the apple's standard method then it works fine.

Code snippet:

1. When using DTCoreText

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

return stringBuilder.generatedAttributedString()!

Input String:

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

Output attributed String:

Earn Instantly!{ CTForegroundColor = " [ (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 0.921569 0.113725 0.113725 1 )"; NSFont = " font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 22.00pt"; NSParagraphStyle = "{base writing direction = -1, alignment = 4, line break mode = 0, default tab interval = 36\nfirst line head indent = 0, head indent = 0, tail indent = 0\nline height multiple = 0, maximum line height = 0, minimum line height = 0\nline spacing adjustment = 0, paragraph spacing = 0, paragraph spacing before = 0\n}"; }

2. When using Apple's standard method:

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

Output attributed String:

Earn Instantly!{ 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), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0"; NSStrokeColor = "kCGColorSpaceModelRGB 0.921569 0.113725 0.113725 1 "; NSStrokeWidth = 0; }

Since I am getting way too many crashes while using Apple's standard method so I want to move to DTCoreText.


Solution

  • Adding following code to options argument worked!!

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

    The reason is setting above attribute to true makes use of NSForegroundColorAttributeName (available iOS 6.0 onwards only) instead of the default kCTForegroundColorAttributeName.