4

サーバーからテキストを取得して TTTAttributedLabel に表示する ios アプリケーションがあります。表示されるテキストは HTML から削除されます。

例えば

元の HTML

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

TTTAttributedLabel でのテキスト表示

Hello World!

ただし、HTML のように「World」という単語をクリックできるようにしたいと考えています。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];

しかし、「World」という単語がテキストに複数回現れる場合、上記のコードは間違っています。

このケースを処理するためのより良い方法を提案できる人はいますか? ありがとう

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 に答える