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

要加载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 = @"

首付5000元,提前付3倍月供,月供3000元(48期)

";

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 ;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值