UILable addAttributes 根据html图片内容进行高度设置

1.设置label的html图片

-(NSMutableAttributedString *)setAttributedString:(NSString *)str
{
    //如果有换行,把\n替换成
//如果有需要把换行加上 str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"
"]; //设置HTML图片的宽度 str = [NSString stringWithFormat:@"%@",[UIScreen mainScreen].bounds.size.width-28,str]; NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil]; //设置富文本字的大小 [htmlString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, htmlString.length)]; //设置行间距 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [htmlString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [htmlString length])]; return htmlString; }

2.设置html图片的高度
计算出来的 height 正好是排版后的高度大小,是 CGFloat 类型,在是在我们设置UIlabel/Cell 高度时,可能存在四舍五入等,最后存在的一点点误差使得 UILabel 显示不全,可能出现缺少一行,上下空白太多等情况;

解决方案:为了确保布局按照我们计算的数据来,可以使用ceil函数对计算的 Size 取整,再加1,确保 UILabel按照计算的高度完好的显示出来; 或者使用方法CGRectIntegral(CGRect rect) 对计算的 Rect 取整,在加1;

-(CGFloat )getHTMLHeightByStr:(NSString *)str
{
    str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"
"]; str = [NSString stringWithFormat:@"%@",[UIScreen mainScreen].bounds.size.width,str]; NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil]; [htmlString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, htmlString.length)]; //设置行间距 NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle1 setLineSpacing:5]; [htmlString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [htmlString length])]; // CGSize contextSize = [htmlString boundingRectWithSize:(CGSize){[UIScreen mainScreen].bounds.size.width-28, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size; CGSize labelSize = [_detailLab sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width-28, MAXFLOAT)]; CGFloat height = ceil(labelSize.height) + 1; return height; }

你可能感兴趣的:(ios)