Adam Nelson Adam Nelson - 11 days ago 8
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 http://example.com to register


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

Answer

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

override func viewDidLoad() {
    super.viewDidLoad()

    // You must set the formatting of the link manually
    let linkAttributes = [
        NSLinkAttributeName: NSURL(string: "https://www.apple.com")!,
        NSForegroundColorAttributeName: UIColor.blue
    ] 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
}
Comments