iosnsattributedstringasyncdisplaykit

Change NSAttributedString html links color


Trying to display a ASTextNode (same as UILabel from AsyncDisplayKit) to display an html text. I simply have to set the label's attributed text.

There is how i work my string :

Using this extension i transform the HTML text into a NSAttributedString :

extension String {
    var html2AttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
            return  nil
        }
    }
    var html2String: String {
        return html2AttributedString?.string ?? ""
    }
}

Then i set my label details :

 self.displayContent = NSMutableAttributedString(attributedString: content.html2AttributedString!)
 self.displayContent?.addAttribute(NSFontAttributeName, value: UIFont.fontMainFeedContentFont(), range: NSRange.init(location: 0, length: self.displayContent!.length))

So i have my label with my font and it's ok, problem is that i can't change the links colors of my label, it's a system blue that i do want.

Any idea how can i change the links' colors ?

Thanks.


Solution

  • I found an answer for this in Swift 4.0

    termsAndPolicyTextView.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.red
    ]
    

    Full code: Note: I can't set multiple color in a single textView.

    let attributedString = NSMutableAttributedString(string: termsAndPolicyText)
    
    attributedString.addAttribute(
        NSAttributedString.Key.link,
        value: "https://google.co.in",
        range: (termsAndPolicyText as NSString).range(of: "Terms or service")
    )
    
    attributedString.addAttribute(
        NSAttributedString.Key.link,
        value: "https://google.co.in", // Todo set our terms and policy link here
        range: (termsAndPolicyText as NSString).range(of: "Privacy & Legal Policy")
    )
    
    attributedString.addAttributes(
        [NSAttributedString.Key.foregroundColor: UIColor.NMSTextColor(with: 0.6)],
        range: NSRange(location: 0, length: termsAndPolicyText.count)
    )
    
    termsAndPolicyTextView.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.termstextViewTextColor()
    ]
    termsAndPolicyTextView.attributedText = attributedString
    termsAndPolicyTextView.textAlignment = .center