Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 494
Adam Nelson Avatar asked Aug 30 '16 23:08

Adam Nelson


People also ask

How do I make a clickable link in text?

Select the text or picture that you want to display as a hyperlink. Press Ctrl+K. You can also right-click the text or picture and click Link on the shortcut menu. In the Insert Hyperlink box, type or paste your link in the Address box.

How can I make a clickable link in an Nsattributedstring?

You just set the "detect links" checkbox on the view in IB, and it detects HTTP links and turns them into hyperlinks. However, that still means that what the user sees is the "raw" link. RTF files and HTML both allow you to set up a user-readable string with a link "behind" it.

How do I change the color of a link in TextView Swift?

You can Change the Hyperlink Color in a TextView by the following: In the Nib file, you can go to the Properties Window and change the Tint to which ever color you want to.


1 Answers

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 ] 
like image 176
Code Different Avatar answered Oct 12 '22 18:10

Code Different