zoukankan      html  css  js  c++  java
  • 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 = @"<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 ;
    
  • 相关阅读:
    上云,你真的只差一本葵花宝典
    Linux Kernel 4.11首个候选版本开放下载
    Windows 10 host where Credential Guard or Device Guard is enabled fails when running Workstation (2146361)
    .NET技术+25台服务器怎样支撑世界第54大网站
    Azure 订阅和服务限制、配额和约束
    python再议装饰器
    python的上下文管理器-1
    python的上下文管理器
    python小知识点
    python做简易记事本
  • 原文地址:https://www.cnblogs.com/GJ-ios/p/10531351.html
Copyright © 2011-2022 走看看