How to Display Clickable Links in Uitextview

How to display clickable links in UITextView

Just select the UITextView in your storyboard and go to "Show Attributes inspector" and select selectable and links. As the image below shows. Make sure Editable is unchecked.

Sample Image

Can't make URL clickable in UITextView

The issue was that User Interaction Enabled wasn't checked at the bottom of the View section of IB's Attributes Inspector.

UITextView with hyperlink text

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
]

Trigger hyper link text click and and normal text click in UITextView

A possible solution is to add a "fake URL" (like a "internal URL Scheme look alike) where there is no link attribute:

attributedText.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedText.length), options: []) { (attribute, range, pointee) in
//If there is no URL => Set our custom one
if attribute == nil {
attributedText.addAttribute(.link, value: "com.myapp.custom", range: range)
}
}

And in this delegate method, check the value of URL.

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print("url: \(URL)")
if url == ... {} else { ... }
return false
}


Related Topics



Leave a reply



Submit