lab添加显示HTML数据

-(void)setHTMLTextToLab:(UILabel *)lab withHTMLStr:(NSString *)htmlStr
{
    
    //str是要显示的字符串
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    [attrString addAttributes:@{NSBaselineOffsetAttributeName: @(5),//设置基线偏移值,取值为 NSNumber (float),正值上偏,负值下偏,可使UILabel文本垂直居中
                                NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, attrString.length)];
    
    lab.attributedText = attrString;
    
    
    //计算html字符串高度
    NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[htmlStr 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){kScreenH - 20, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    //
    lab.textAlignment = NSTextAlignmentCenter;
    lab.numberOfLines = 0 ;
    lab.frame = CGRectMake(0, lab.frame.origin.y, [UIScreen mainScreen].bounds.size.width, textSize.height);
}

 

posted @ 2018-09-13 09:14  刚刚888  阅读(136)  评论(0编辑  收藏  举报