要加載html字符串,用人說,直接用webView啊!但是,有時候我們只需要顯示2行文字,如此少的內容卻要在復雜的UI排版中加入一個占用資源較多的webview,得不償失。這里要說的是,我們其實可以用label即可加載html字符的,用富文本轉一下html字符串即可。
//創建UILabel
_Test_Lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 200, 200)];
_Test_Lbl.backgroundColor = [UIColor yellowColor];
_Test_Lbl.textColor = [UIColor redColor];
[self.view addSubview:_Test_Lbl];
服務端返回的不一定都是純字符串,有可能是帶有HTML標簽的
//html字符串轉換為富文本
NSString *html = @"<p style='color:green'>首付<span style='color:#e83c36;'>5000元</span>,提前付<span style='color:red'>3倍月供</span>,月供<span style='color:red'>3000元</span>(48期)</p>";
NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
_Test_Lbl.attributedText = attStr;
//富文本轉換為html(最后相當於整個網頁代碼,會有css等)
NSDictionary *dic = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:@(NSUnicodeStringEncoding)};
NSData *data = [attStr dataFromRange:NSMakeRange(0, attStr.length) documentAttributes:dic error:nil];
NSString *htmlstr = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
_Test_Lbl.text = htmlstr;
//計算html字符串高度
//計算html字符串高度
NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil];
[htmlString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, htmlString.length)];
CGSize textSize = [htmlString boundingRectWithSize:(CGSize){ScreenWidth - 20, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
return textSize.height ;
