Search code examples
htmliosiphoneuilabeltttattributedlabel

How to make an HTML anchor as clickable link in TTTAttributedLabel?


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


Solution

  • 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];