场景:
项目中的简介(关于)页面, 服务器给返回了Html的语句, 展示相关的内容
方案:
- 想用WKWebView去加载, 但是, WK的在轻量级需求而言, 消耗资源大就成了其短板.
- 使用UILabel + 富文本
对比两个方案, 开启WK的消耗资源大, 再加上当前页面只是文字展示, 所以, 方案二是相对而言的最佳方案.
解决:
在解决的过程中, 本来以为只是展示出就可以了, 发现Html中包含了href的超链接, 所以, 如果你的项目中, 也有包含href的超链接, 那么可以参考步骤2和步骤3, 如果没有只看步骤1即可
1. 将html转换成富文本
重点为: NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType
- (NSMutableAttributedString *)getContentHtml:(NSString *)content {
NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)};
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
// 设置段落格式
NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
para.lineSpacing = 8;
para.paragraphSpacing = 10;
[attStr addAttribute:NSParagraphStyleAttributeName value:para range:NSMakeRange(0, attStr.length)];
// 设置文本的Font
[attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, attStr.length)];
return attStr;
}
2. 给UILabel添加点击事件, 注意, 这里需要将UILabel的用户交互打开
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLink)];
// 打开用户交互
self.contentLabel.userInteractionEnabled = YES;
[self.contentLabel addGestureRecognizer:tap];
3. 处理点击UILabel点击富文本中的超链接
解析html中的链接 NSTextCheckingTypeLink
- (void)clickLink {
NSString *chatStr = @"这里需要填写Html内容, 不是UILabel的text 或者 NSMutableAttributedString";
NSDataDetector *detector= [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *checkArr = [detector matchesInString:chatStr options:0 range:NSMakeRange(0, chatStr.length)];
//判断有没有链接
if(checkArr.count > 0) {
LTCWebViewController *webVC = [[LTCWebViewController alloc] init];
if (checkArr.count > 1) { //网址多于1个时让用户选择跳哪个链接
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择要打开的链接" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
for (NSTextCheckingResult *result in checkArr) {
NSString *urlStr = result.URL.absoluteString;
[alertController addAction:[UIAlertAction actionWithTitle:urlStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
webVC.urlString = urlStr;
[self.navigationController pushViewController:webVC animated:YES];
}]];
}
[self presentViewController:alertController animated:YES completion:nil];
}else {//一个链接直接打开
webVC.urlString = [checkArr[0] URL].absoluteString;
[self.navigationController pushViewController:webVC animated:YES];
}
}
}
该博客介绍了在iOS应用中如何处理HTML内容并展示在UILabel上,同时实现富文本中的超链接点击事件。首先,通过将HTML转换为富文本来显示内容,然后开启UILabel的用户交互并添加点击手势识别器。当点击超链接时,利用NSDataDetector解析链接并弹出选择对话框,用户可以选择打开多个链接中的任一网页。此方法适用于只需文字展示且包含超链接的轻量级场景,避免了WKWebView资源消耗大的问题。


被折叠的 条评论
为什么被折叠?



