计算富文本高度
参数为:字符串、行间距、字体大小、宽度size、
h1 = [self calculateLabelHeightWithText:infoVo.title lineSpace:7 fontName:[UIFont systemFontOfSize:30] size:CGSizeMake(SCREEN_WIDTH-118-24, 2000) label:_titleLabel];
//增加判断为一行,,去掉行间距。
- (CGFloat)calculateLabelHeightWithText:(NSString*)text lineSpace:(NSInteger)lineSpace fontName:(UIFont*)fontName size:(CGSize)size label:(UILabel*)label
{
CGFloatheight =0;
if(text.length>0) {
// 计算内容高度,判断显示几行
NSString*firstWord = [textsubstringToIndex:1];
CGFloatoneRowHeight = [firstWordsizeWithAttributes:@{NSFontAttributeName:fontName}].height;
NSDictionary*attributes =@{NSFontAttributeName:fontName};
CGSize textSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
CGFloatrows = textSize.height/ oneRowHeight;
//此处为一行时候
if(rows ==1) {
lineSpace =0;
height = oneRowHeight;
}elseif(rows >1) {
height = (oneRowHeight + lineSpace) * rows;
}
if(label) {
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStylesetLineSpacing:lineSpace];
[stringaddAttribute:NSParagraphStyleAttributeNamevalue:paragraphStylerange:NSMakeRange(0,text.length)];
[labelsetAttributedText:string];
}
}
returnheight;
}
//补充:正常文本不是1行的话,,,会设置相关间距,,,但是,当文本只有一行,,,间距存在意义不大。。一般设置为0去显示。 所以此处,,增加判断 此文本是否是一行。
//判断是否一行
- (BOOL)calculateLabelHeightWithText1:(NSString*)text lineSpace:(NSInteger)lineSpace fontName:(UIFont*)fontName size:(CGSize)size label:(UILabel*)label{
BOOLheight =NO;
if(text.length>0) {
// 计算内容高度,判断显示几行 NSString*firstWord = [textsubstringToIndex:1];
CGFloatoneRowHeight = [firstWordsizeWithAttributes:@{NSFontAttributeName:fontName}].height; NSDictionary*attributes =@{NSFontAttributeName:fontName};
CGSize textSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size; CGFloatrows = textSize.height/ oneRowHeight;
if(rows ==1) {
lineSpace =0;
height =YES;
}elseif(rows >1) {
height =NO;
}
}
returnheight;
}