Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel - string as text and links

I have a UILabel whose text I am getting from a server. Some of the text is to be identified as links, and on touching those links some action should be performed. e.g.

NSString *str = @"My phone number is 645-345-2345 and my address is xyz";

This is the complete text for UILabel. I have only one UILabel for displaying this text (Text is dynamic. I just gave an example.). On clicking these links I need to perform actions like navigating to some different screen or make a call.
I know that I can display such text with help of OHAttributedLabel. And the links can be displayed as follows :

[label1 addCustomLink:[NSURL URLWithString:@"http://www.foodreporter.net"] inRange:[txt rangeOfString:someString]];   

But I wonder how can I make these text links perform some action like navigation to different screen or making a call.
Let me know if more explanation is required.

like image 422
Nitish Avatar asked Jan 12 '12 17:01

Nitish


People also ask

How do you display HTML formatted text in UILabel Swift?

To render this text properly in UILabel or UITextView, you need to convert it to NSAttributedString . NSAttributedString has built-in support for this conversion. First, we need to convert HTML string to Data . let htmlString = "This is a <b>bold</b> text."


1 Answers

You can add custom actions to any of the available UILabel replacements that support links using a fake URL scheme that you'll intercept later:

TTTAttributedLabel *tttLabel = <# create the label here #>; NSString *labelText = @"Lost? Learn more."; tttLabel.text = labelText; NSRange r = [labelText rangeOfString:@"Learn more"];  [tttLabel addLinkToURL:[NSURL URLWithString:@"action://show-help"] withRange:r]; 

Then, in your TTTAttributedLabelDelegate:

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {     if ([[url scheme] hasPrefix:@"action"]) {         if ([[url host] hasPrefix:@"show-help"]) {             /* load help screen */         } else if ([[url host] hasPrefix:@"show-settings"]) {             /* load settings screen */         }     } else {         /* deal with http links here */     } } 

TTTAttributedLabel is a fork of OHAttributedLabel.

If you want a more complex approach, have a look to Nimbus Attributed Label. It support custom links out-of-the-box.

like image 151
djromero Avatar answered Sep 30 '22 20:09

djromero