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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/251796.html
標籤:其他
下一篇:計算器專案
