1.设置label的html图片
-(NSMutableAttributedString *)setAttributedString:(NSString *)str
{
//如果有换行,把\n替换成<br/>
//如果有需要把换行加上
str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"];
//设置HTML图片的宽度
str = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@",[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:@"<br/>"];
str = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@",[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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。