UILable显示
NSString *str = @"<p>hello</p> <p>i am a demo</p>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
_titleLab.attributedText = attrStr;
网络解析后 有一个HTML字符串 需要在label显示(一般是要求显示的内容有颜色 字体 背景颜色的变化) 如果不做处理 显示的就是HTML代码内容 处理方法如下 原文链接
已知网络请求得到一个HTML 字符串 self.HTMLstring
1.富文本显示 不考虑高度自适应
NSMutableAttributedString *str= [[NSMutableAttributedString alloc] initWithData:[self.HTMLstring dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
[str addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17.0] range:NSMakeRange(0, str.length)];
synthesizeCell.nameLabel.attributedText = str;
2.富文本label的高度自适应
NSMutableAttributedString *str= [[NSMutableAttributedString alloc] initWithData:[self.HTMLstring dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
[str addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0, str.length)];(字体font是自定义的 要求和要显示的label设置的font一定要相同)
CGRect rect = [self.contentLabel.attributedText boundingRectWithSize:CGSizeMake(WIDTH - 330 *FITWIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
self.contentLabel.frame = CGRectMake(115 *FITWIDTH, 110 *FITWIDTH, WIDTH - 330 *FITWIDTH, rect.size.height);
self.contentLabel.attributedText = str;
网页显示
NSString *str = @"<p>hello</p> <p>i am a demo</p>";
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bonus];
[self.view addSubview:webView];
[webView loadHTMLString:str baseURL:nil];