4

I have an ios application which fetch a piece of text from server and display it in a TTTAttributedLabel. The text displayed is stripped from a HTML.

E.g.

Original HTML

<p>
  Hello <a href="http://www.google.com">World!</a>
</p>

Text display in TTTAttributedLabel

Hello World!

However, I would like the word "World" be clickable as in HTML. I know that TTTAttributedLabel can be used like

TTTAttributedLabel *tttLabel = <# create the label here #>;
NSString *labelText = @"Hello World!";
tttLabel.text = labelText;
NSRange r = [labelText rangeOfString:@"World"]; 
[tttLabel addLinkToURL:[NSURL URLWithString:@"http://www.google.com"] withRange:r];

But if the word "World" appears more than once in the text, the above code will be wrong.

Can any one suggest a better method to handle this case? Thanks

cppcho
  • 319
  • 2
  • 14

1 Answers1

10

I finally ends up using NSAttributedString to handle this. Here is my code.

TTTAttributedLabel *_contentLabel = [[TTTAttributedLabel alloc] init];
_contentLabel.backgroundColor = [UIColor clearColor];
_contentLabel.numberOfLines = 0;
_contentLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
_contentLabel.delegate = self;

_contentLabel.text = [[NSAttributedString alloc] initWithData:[[_model.content trimString]
                                                               dataUsingEncoding:NSUnicodeStringEncoding]
                                                      options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                           documentAttributes:nil
                                                        error:nil];

Also in my app I need to update the font size of _contentLabel on the fly. And here is the code.

NSFont *newFont = ...; // new font

NSMutableAttributedString* attributedString = [_contentLabel.attributedText mutableCopy];

[attributedString beginEditing];
[attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
    [attributedString removeAttribute:NSFontAttributeName range:range];
    [attributedString addAttribute:NSFontAttributeName value:newFont range:range];
}];
[attributedString endEditing];

_contentLabel.text = [attributedString copy];
cppcho
  • 319
  • 2
  • 14
  • 1
    Thanks that worked for me as well..Thanks! I had a text from server that had the href tags... – cableload Feb 11 '16 at 15:42
  • 1
    If you are using swift it will give an error if you try to assign an `NSAttributedString` to the `TTTAttributedLabel`'s `text` variable. Use `.setText(AnyObject)` instead and everything will work as it should. – MineConsulting SRL Jun 21 '16 at 09:02