iOS UILabel加载HTML文本

项目中有时候接口返回HTML格式的文本,客户端显示,第一反应用webView啊,但是返回的文本不多,使用耗能极大的webView得不偿失啊,所以这时候才用UILabel或是UITextView加载HTML格式的文本。

具体测试代码如下:


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.testLabel];
    [self loadHtmlTOLabel];
}

- (void)loadHtmlTOLabel {
    //返回的HTML文本
    NSString *htmlStr = @"Enter <a href=\"https://app-gearbest.com.trunk.s1.egomsl.com/my-coupon.html\" target=\"_blank\"><b>\"My Coupon\"</b></a> page to.3. Go to your “My Coupon” page to view your Coupon!<br>4. GearBest reserves the right to amend this activity. For any queries, please contact our Support Staff. (<a href=\"https://support.gearbest.com\" target=\"_blank\">https://support.gearbest.com</a>)";
    
    //富文本,两种都可以
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    NSData *data = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];
    //或者
//    NSDictionary *option = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType};
//    NSData *data = [htmlStr dataUsingEncoding:NSUnicodeStringEncoding];
    
    //设置富文本
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    //设置段落格式
    NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
    para.lineSpacing = 7;
    para.paragraphSpacing = 10;
    [attStr addAttribute:NSParagraphStyleAttributeName value:para range:NSMakeRange(0, attStr.length)];
    self.testLabel.attributedText = attStr;
    
    //设置文本的Font没有效果,默认12字号,这个只能服务器端控制吗? 暂时没有找到方法修改字号
    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, attStr.length)];
    //计算加载完成之后Label的frame
    CGSize size = [self.testLabel sizeThatFits:CGSizeMake(300, 1000)];
    //也可以使用这个方法,对应好富文本字典
//    CGSize size = [self.testLabel.attributedText boundingRectWithSize:CGSizeMake(300, 1000) options:@{} context:nil];
    self.testLabel.frame = CGRectMake(50, 100, size.width, size.height);
}

#pragma mark setter and getter
- (UILabel *)testLabel {
    if (!_testLabel) {
        _testLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 100)];
        _testLabel.textColor = [UIColor blackColor];
        _testLabel.backgroundColor = [UIColor whiteColor];
        _testLabel.textAlignment = NSTextAlignmentCenter;
        _testLabel.numberOfLines = 0;
        //怎么设置字号都没有效果
        _testLabel.font = [UIFont systemFontOfSize:20];
    }
    return _testLabel;
}

这里要说明几个问题:

1.加载HTML文本之后,可以调整其显示的段落格式。
2.可能不能设置字号UIFont,貌似只能是服务器端控制。知道的吧友还请告知一下,感激不尽。
3.可以求出显示完成之后控件的大小,富文本长度等信息。
4.当服务器返回的不是标准的HTML格式文本时,先进行一下转化。

//将 &lt 等类似的字符转化为HTML中的“<”等 
- (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"

    return string;
}

**5.还有一个可能会出现的问题。

当你加载完HTML显示正常之后,在这个界面停留几分钟,可能会出现闪退,报错webView Thread问题。可能会遇见,可能也不会,暂时不知道原因。解决办法:将加载HTML富文本放在线程里

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
             dispatch_async(dispatch_get_main_queue(), ^{
                
                 self.testLabel.attributedText = attributeStr;
             });
        });

6.至于怎么获取跳转链接等问题,可以参考YYLabel。

反正我是没有找到自动跳转链接功能,只能自己筛选出来链接,进行跳转。
有知道更好办法的吧友,请告知下,O(∩_∩)O谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,766评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,772评论 4 61
  • 为什么读了哲学明白好多让人难受的人间事、却还是想读下去? 用john stuart mill的话来讲,宁做痛苦的人...
    cloverblue阅读 3,674评论 0 1
  • 如果你想将你自己的代码发布到市面上;或者有兴趣制作内部使用的你自己的 podspecs 仓库 —— 这儿就是你在寻...
    RX78178阅读 1,886评论 0 0
  • 这是一个医学院背景金发妹子去一个无名海滩寻找生活中的意义然而真~~的找到了生命的意义——毕竟MM没想过冲浪时会遇见...
    Falada阅读 2,629评论 0 0

友情链接更多精彩内容