Lable 显示 Html 标签 (小技巧)

使用NSHTMLTextDocumentType从HTML创建的NSAttributedString;

 

这种方法有利有弊。大概看了一下 ,坑多。我感觉还好吧。像下面的第一段的富文本,如果拼起来会疯的,用下面方法。很容易搞定。

Lable 显示 Html 标签 (小技巧)_第1张图片

-(void)testHtmlText{
    
    UILabel *htmlLa = [[UILabel alloc]init];
    htmlLa.frame = CGRectMake(100, 150, 200, 200);
    [self.view addSubview:htmlLa];
    htmlLa.font = [UIFont systemFontOfSize:14];
    htmlLa.numberOfLines = 0;
    htmlLa.textAlignment = NSTextAlignmentCenter;
    
    NSString *str = @"今天出去吃饭花了还剩100元 ,还剩99元 ,路上捡了666元,\n1234567,\n7654321";
          NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
        htmlLa.attributedText = attrStr;
    
    
    UILabel *htmlLa2 = [[UILabel alloc]init];
       htmlLa2.frame = CGRectMake(100, 400, 200, 200);
       [self.view addSubview:htmlLa2];
       htmlLa2.font = [UIFont systemFontOfSize:14];
       htmlLa2.numberOfLines = 0;
    
    NSString *style = @"";
   NSString *html = @"

哦哦佛鳄我放假诶哦忘记哦加尔文.

A whole bunch of sample text goes right here,n n No

Now here's another paragraph that unfortunately has an extra line underneath the text adding undesired padding to the label. :(

"; NSString *styledHtml = [NSString stringWithFormat:@"%@%@", style, html]; // 使用utf-8 汉字会出现乱码 // htmlLa2.attributedText = [[NSMutableAttributedString alloc] initWithData:[styledHtml dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil]; htmlLa2.attributedText = [[NSMutableAttributedString alloc] initWithData:[styledHtml dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil]; }

 

你可能感兴趣的:(iOS开发)