How to color HTML links using NSAttributedString in iOS

I'm using UITextView to display HTML content, which works great apart from links. I can set the font and color for normal text like this:

let str = "<font size='4' style='color:red'>text is red</font>"

      

which works fine. But when you try to colorize such a link, nothing happens.

let str = "some text <a href='http://stackoverflow.com' style='color:red'> 
              link is not red!?</a> some text <a href='http://google.com' 
              style='color:green'> link is not green!?</a>"

      

This is how I set the string to the UITextView.

var attrStr = NSAttributedString(
        data: str.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil,
        error: nil)
myTextView.attributedText = attrStr

      

EDIT:

You can edit all link colors with this code. It is not possible to have different colors depending on the link, although this was what I was looking for.

myTextView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.greenColor()]

      

+3


source to share


1 answer


On iOS 7, you can set the tintColor of the UITextView. This affects the link color, as well as the cursor line and selected text color.

iOS 7 also added a new property to the UITextView called linkTextAttributes that appears to give you complete control over the style of links.

Refer Link: Is it possible to change the color of autodiscovered links in UITextView?



IOS Developer Library Library: iOS Developer UITextView Class

Please refer to the above link, I hope it helps you.

0


source







All Articles