1.计算cell高度
-
(CGFloat)sizeForClientArea:(JAnnouncementContent *)msgModel withViewWidth:(CGFloat)width {
CGFloat cellHeight = 80 ;NSAttributedString *attributedString = [self setAttributedString:msgModel.content font:[UIFont systemFontOfSize:12] lineSpacing:10];
CGFloat height = [self getHTMLHeightByStr:msgModel.content font:[UIFont systemFontOfSize:12] lineSpacing:10 width:(SCREEN_WIDTH - 2 * 17 - 2 * 11)];return height+cellHeight;
}
2./**
html 富文本设置
@param str html 未处理的字符串
@param font 设置字体
@param lineSpacing 设置行高
@return 默认不将 \n替换
返回处理好的富文本
*/
-(NSMutableAttributedString *)setAttributedString:(NSString *)str font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing
{
//如果有换行,把\n替换成
//如果有需要把换行加上
// str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"
"];
//设置HTML图片的宽度
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:font} range:NSMakeRange(0, htmlString.length)];
//设置行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];
[htmlString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [htmlString length])];
return htmlString;
}
3./**
计算html字符串高度
@param str html 未处理的字符串
@param font 字体设置
@param lineSpacing 行高设置
@param width 容器宽度设置
@return 富文本高度
*/
-(CGFloat )getHTMLHeightByStr:(NSString *)str font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing width:(CGFloat)width
{
// str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"
"];
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:font} range:NSMakeRange(0, htmlString.length)];
//设置行间距
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setLineSpacing:lineSpacing];
[htmlString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [htmlString length])];
CGSize contextSize = [htmlString boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
return contextSize.height ;
}