gpt4 book ai didi

html - 如何在 TTTAttributedLabel 中将 HTML anchor 设为可点击链接?

转载 作者:可可西里 更新时间:2023-11-01 05:21:05 25 4
gpt4 key购买 nike

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

例如

原始 HTML

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

TTTAtributedLabel 中的文本显示

Hello World!

但是,我希望“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];

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

谁能建议一种更好的方法来处理这种情况?谢谢

最佳答案

我最终使用 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];

关于html - 如何在 TTTAttributedLabel 中将 HTML anchor 设为可点击链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26032429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com