利用UITextView加载接口返回的HTML标签、改变超链接文字的颜色和点击事件。
- (UITextView *)textView {
if (!_textView) {
_textView = [[UITextView alloc] init];
_textView.backgroundColor = [UIColor clearColor];
_textView.editable = NO;
_textView.scrollEnabled = NO;
_textView.delegate = self;
_textView.font = [UIFont systemFontOfSize:15];
_textView.textContainerInset = UIEdgeInsetsZero;
_textView.textContainer.lineFragmentPadding = 0;
_textView.layoutManager.allowsNonContiguousLayout = NO;
_textView.showsVerticalScrollIndicator = NO;
_textView.showsHorizontalScrollIndicator = NO;
}
return _textView;
}
1、显示
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
self.textView.attributedText = attributedString;
2、改变超链接文字颜色(linkTextAttributes 超链接相关属性)去掉下划线接口返回的HTML可以处理,自己也可以处理
self.textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor redColor]};
3、超链接点击事件
UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
//URL:就是那个跳转链接
NSString *urlStr = URL.absoluteString;
ViewController *vc = [[ViewController alloc] initWithRequestUrl:urlStr];
[self.navigationController pushViewController:vc animated:YES];
//返回NO,如果返回YES就会跳到Safari
return NO;
}
网友评论