您的位置:首页 > 产品设计 > UI/UE

iOS UIlabel怎么加载html字符串 富文本的用法

2016-08-26 17:49 351 查看
要加载html字符串,用人说,直接用webView啊!但是,有时候我们只需要显示2行文字,如此少的内容却要在复杂的UI排版中加入一个占用资源较多的webview,得不偿失。这里要说的是,我们其实可以用label即可加载html字符的,用富文本转一下html字符串即可。

//str是要显示的字符串
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];

[attrString addAttributes:@{NSBaselineOffsetAttributeName: @(5),//设置基线偏移值,取值为 NSNumber (float),正值上偏,负值下偏,可使UILabel文本垂直居中
NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, attrString.length)];

self.descLabel.attributedText = attrString;

//计算html字符串高度
NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[str 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 ;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息