Text View Links


Making links tappable inside UITextView is pretty trivial, but I always forget a thing or two.

Turn Off Editing

If the text view is editable then the user's interaction with the text will be to select and revise the text rather than being able to tap on links so the first thing you'll want to do is to disable editing

textView.editing = false

Turn on all data detection types

This will allow urls, phone numbers, and addresses all to be automatically detected for you

textView.dataDetectorTypes = .All

Set Text

You could alternatively set the attributedText property if you'd like finer control over the styling, but to keep it simple you can just use the text property:

textView.text = "Google: http://google.com"


There are two easy ways to style all links to look the same. One way is to just set the tintColor of the textView. The other way is to pass in an attribute dictionary which will allow you to even do things like underline

 textView.tintColor = UIColor.redColor()
 // OR:
 textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]

Complete Example:

Here is a complete example showing all three data detector types

class ViewController: UIViewController {

    private var textView: UITextView!

    override func viewDidLoad() {
        textView = UITextView(frame: CGRect(x: 20, y: 20, width: 290, height: 70))
        //textView.tintColor = UIColor.redColor()
        textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
        textView.editable = false
        textView.dataDetectorTypes = .All
        textView.text = "Google \n" +
        "http://google.com\n" +
        "1600 Amphitheatre Pkwy, Mountain View, CA 94043 \n" +
        "(650) 253-0000"

Other Alternatives:

Some of the other alternatives could be UILabel, which doesn't allow tapping or doing custom styling in a web view which might present other challenges.