UIWebView可以加载HTML数据毋庸置疑,但是我们也都知道webView的性能不高,单个webView的话可能还好,但是如果我的tableviewcell中的内容是HTML数据,这时候再用webiew去加载的话,相当于在tableviewcell中嵌套多个webview,如果cell的个数多的话,那么性能自然会受到不小的影响。但是因为cell中显示的数据是HTML类型的,说白了也就是可以图文混排,那怎么去实现呢?如果用CoreText进行图文混排的话,那么还得将HTML数据解析出来,工作量不小(还有我也不会解析HTML数据)。这时候UILabel或者UITextView的富文本属性attributedText
就很好的发挥作用了。通过将返回的HTML数据转换成NSMutableAttributedString
,再用label或者textView的attributedText
属性,我们就可以直接显示HTML格式的数据了。
由于对NSMutableAttributedString
的操作是比较耗时的,所以不建议将HTML转化成NSMutableAttributedString
的操作放在cell里面进行,我们可以将这个转换放在获取数据的方法里,提前将HTML数据转化好,在cell里赋值的时候直接使用已经转换好的内容即可。
-(NSMutableAttributedString *)changeHtmlStringToAttributeString:(NSString *)htmlString{
NSString *newString = htmlString;
//图片自适应宽高,只限制图片的最大显示宽度,这样就能做到自适应
newString =[NSString stringWithFormat:@"<html>"
"<head>"
"</style>"
"<style>*{
margin:3px 0px 3px 0px;padding:0 ;max-width:%f;}</style>"
"</head>"
"<body>%@</body>"
"</html>",self.view.frame.size.width-30,newString];
NSData *data = [newString dataUsingEncoding:NSUnicodeStringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSMutableAttributedString *htmlAttribute = [[NSMutableAttributedString alloc] initWithData:data
options:options
documentAttributes:nil
error:nil];
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//设置文字的行间距
[paragraphStyle setLineSpacing:5];
[htmlAttribute addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [htmlAttribute length])];
//设置文字的颜色
[htmlAttribute addAttribute:NSForegroundColorAttributeName value:RGBACOLOR(51, 51, 51, 1) range:NSMakeRange(0, htmlAttribute.length)];
//设置文字的大小
[htmlAttribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, html