iOS UILabel加载HTML

记录一下
//返回的HTML文本 
    NSString *str = @"正确的追求犹如永远指向光明的指南针,帮助我们加大马力,驶向前方;正确的追求就像我们额上熏黑的矿灯,照亮我们前行的道路;正确的追求就是我们成功的入场卷,越早的订票,就有越好座位。都说我们是花样年华,充满生机和活力,那就赶快行动起来,找到自己人生的追求,共同打开成功的大门吧!";
    NSString *HTMLString = [NSString stringWithFormat:@"%@", str ];
    

    NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                              NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)
                              };
    NSData *data = [HTMLString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];   // 调整行间距
    paragraphStyle.lineSpacing = 8.0;
    paragraphStyle.alignment = NSTextAlignmentJustified;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
    
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, attributedString.length)];
    
    UILabel *HTMLLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, [UIScreen mainScreen].bounds.size.width - 40, 0)];
    HTMLLabel.backgroundColor = [UIColor cyanColor];
    HTMLLabel.numberOfLines = 0;
    HTMLLabel.attributedText = attributedString;
    [HTMLLabel sizeToFit];
    [self.view addSubview:HTMLLabel];

效果如下:


iOS UILabel加载HTML_第1张图片
效果图

你可能感兴趣的:(iOS UILabel加载HTML)