4

我有一个 ios 应用程序,它从服务器获取一段文本并将其显示在 TTTAttributedLabel 中。显示的文本从 HTML 中剥离。

例如

原始 HTML

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

TTTAttributedLabel 中的文本显示

Hello World!

但是,我希望“世界”这个词在 HTML 中是可点击的。我知道 TTTAttributedLabel 可以像这样使用

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

但是如果“世界”这个词在文本中出现了不止一次,上面的代码就会出错。

有人可以提出一种更好的方法来处理这种情况吗?谢谢

4

1 回答 1

10

我终于NSAttributedString用来处理这个了。这是我的代码。

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

同样在我的应用程序中,我需要_contentLabel即时更新字体大小。这是代码。

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];
于 2014-11-17T04:25:01.773 回答