UITextView with hyperlink text

Adam Nelson picture Adam Nelson · Aug 31, 2016 · Viewed 45.7k times · Source

With a non-editable UITextView, I would like to embed text like this in iOS9+:

Just click here to register

I can create a function and manipulate the text but is there a simpler way?

I see that I can use NSTextCheckingTypeLink so getting the text clickable without the 'click here' part is straightforward in Interface Builder:

Just http://example.com to register

I'm using Xcode 8 and Swift 3 if that's relevant.

Answer

Code Different picture Code Different · Aug 31, 2016

Set isEditable = false or the text view will go into text-editing mode when user taps on it.

Swift 4 and later

let attributedString = NSMutableAttributedString(string: "Just click here to register")
let url = URL(string: "https://www.apple.com")!

// Set the 'click here' substring to be the link
attributedString.setAttributes([.link: url], range: NSMakeRange(5, 10))

self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false

// Set how links should appear: blue and underlined
self.textView.linkTextAttributes = [
    .foregroundColor: UIColor.blue,
    .underlineStyle: NSUnderlineStyle.single.rawValue
]