引言
应用场景:使用原生视图UILabel显示服务端返回的带有HTML标签的内容
I 、 html转换为富文本
NSString *html = @"<p style='color:green'>博客<span style='color:#e83c36;'><a>https://kunnan.blog.csdn.net/<a/></span><br/>微信公众号:<span style='color:red'>iOS逆向</span><br/>“订阅”一次 ,享受终身服务的快乐。</br><span style='color:red'>专注《iOS应用逆向与安全》</span>(包括iOS基础)</p>"; NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
II、富文本转换为html
- (void)NSAttributedStringtohtmlWith:(NSAttributedString*)attStr{ NSDictionary *dic = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:@(NSUnicodeStringEncoding)}; NSData *data = [attStr dataFromRange:NSMakeRange(0, attStr.length) documentAttributes:dic error:nil]; NSString *str = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding]; NSLog(@"NSAttributedStringtohtmlWith:%@",str); [self gotoAXWebViewControllerWithHtmlstr:str]; }
III、加载本地HTML文件
1、文章:https://kunnan.blog.csdn.net/article/details/90579369 2、原理:`使用[_webView loadHTMLString:html baseURL:baseURL]; 进行代码加载
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; [self loadHTMLString:_HTMLString baseURL:_baseURL];
`
- 例子
#import <AXWebViewController/AXWebViewController.h> - (void)gotoAXWebViewControllerWithHtmlstr:(NSString*)html{ NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; AXWebViewController *webVC = [[AXWebViewController alloc] initWithHTMLString:html baseURL:baseURL]; UINavigationController *tmp = [[UINavigationController alloc]initWithRootViewController:webVC]; webVC.showsToolBar = NO; webVC.navigationController.navigationBar.translucent = NO; webVC.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.100f green:0.100f blue:0.100f alpha:0.800f]; webVC.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.996f green:0.867f blue:0.522f alpha:1.00f]; //webVC.navigationType = AXWebViewControllerNavigationToolItem; // webVC.showsToolBar = YES; [self presentViewController:tmp animated:YES completion:^{ } ]; }