How can I make a clickable link in an NSAttributedString?

Duncan C picture Duncan C · Feb 7, 2014 · Viewed 219.8k times · Source

It's trivial to make hyperlinks clickable in a UITextView. 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.

It's easy to install attributed text into a text view (or a UILabel or UITextField, for that matter.) However, when that attributed text includes a link, it is not clickable.

Is there a way to make user-readable text clickable in a UITextView, UILabel or UITextField?

The markup is different on SO, but here is the general idea. What I want is text like this:

This morph was generated with Face Dancer, Click to view in the app store.

The only thing I can get is this:

This morph was generated with Face Dancer, Click on http://example.com/facedancer to view in the app store.

Answer

ujell picture ujell · Feb 7, 2014

Use NSMutableAttributedString.

NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"Google"];
[str addAttribute: NSLinkAttributeName value: @"http://www.google.com" range: NSMakeRange(0, str.length)];
yourTextView.attributedText = str;

Edit:

This is not directly about the question but just to clarify, UITextField and UILabel does not support opening URLs. If you want to use UILabel with links you can check TTTAttributedLabel.

Also you should set dataDetectorTypes value of your UITextView to UIDataDetectorTypeLink or UIDataDetectorTypeAll to open URLs when clicked. Or you can use delegate method as suggested in the comments.