Adam Nelson Adam Nelson - 1 year ago 160
Swift Question

UITextView with hyperlink text

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 to register

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

Answer Source

Set your view controller to conform to UITextViewDelegate and a the following code:

override func viewDidLoad() {

    // You must set the formatting of the link manually
    let linkAttributes = [
        NSLinkAttributeName: NSURL(string: "")!,
    ] as [String : Any]

    let attributedString = NSMutableAttributedString(string: "Just click here to register")

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

    self.textView.delegate = self
    self.textView.attributedText = attributedString

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    return true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download