I have a label inside tableview cell and I need to show the url inside the label text as hypertext with blue colour and underline. The link should redirect to particular webpage on tap which means the default OS browser.
Asked
Active
Viewed 956 times
2 Answers
1
You should use library such as the well known TTTAttributedLabel.
Basically, you add a label in storyboard, set its custom class to TTTAttributedLabel
, and make an IBOutlet
for it. Then, with some code, you add an action to some part of the text. In Swift
, this could be this kind of code :
let name = "tomo"
let string = "My name is \(name)"
label.text = string
let nsString = string as NSString
let range = nsString.rangeOfString(name)
let url = NSURL(string: "http://www.urlToRedirect.com")!
label.addLinkToURL(url, withRange: range)
Code taken from this answer.
If you want to automatically detect links in the strings, the library is also able to do it : Links and Data Detection
Hope this helps :)

AnthoPak
- 4,191
- 3
- 23
- 41
-
How to identify the url from a label text and to show the url as a blue color link with clickable feature. The above codes add a url to an existing string – Sona Jun 28 '18 at 12:25
-
Okay, so I guess you don't know the string in advance (probably an answer from web service). TTTAttributedLabel has a feature to detect links in string. Take a look at https://github.com/TTTAttributedLabel/TTTAttributedLabel#links-and-data-detection, should be pretty easy to implement with above code :) – AnthoPak Jun 28 '18 at 12:37
-
Thank you :) Highlighting the url is working properly. But the function didSelectLinkWith url is not calling, I have added the TTTAttributedLabelDelegate also. How can I add the click function when a user taps the url. – Sona Jun 28 '18 at 13:07
-
https://stackoverflow.com/a/18645581/10005005 This solved my issue. Thank You So Much for your answer @AnthoPak – Sona Jun 28 '18 at 13:27
-
@Zeona Sorry, i've just seen your comments. Glad to see you've solve your issue. Would have been hard for me to help on your second issue, without code ;) – AnthoPak Jun 28 '18 at 14:39
0
You can do it by a hack like customize UILabel
as you want and add UITapGestureRecognizer
to it.

Vijay Kharage
- 401
- 4
- 11