How to color HTML links using NSAttributedString in iOS

1.7k views Asked by At

Im using a UITextView to display HTML content which works fine except links. I can set font and color for normal text like this:

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

which works just fine. But when trying to color the link like this 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:

Can edit all link colors with this code. Not possible to have different colors depending on the link though, which was what I was looking for.

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

There are 1 answers

1
hpDev_iOS On

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

iOS 7 also added a new property to UITextView called linkTextAttributes which would appear to let you fully control the link style.

Refer Link : Can I change the color of auto detected links on UITextView?

iOS Developer Library Link : iOS Developer UITextView Class

Refer the above link, i hope this will help to u.