iOS UILabel加载HTML文本

3,305 阅读2分钟
项目中有时候接口返回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谢谢!