[iOS]UILabel计算文本高度
// 计算字符串高度
+ (float)jisuanLabHighWithString:(NSString *)string Width:(float)width FontSize:(float)size {
UIFont *font = [UIFont systemFontOfSize:size];
// NS_AVAILABLE(10_11, 7_0)
CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil];
return rect.size.height;
}
/// 获取固定宽度的文本高度
+ (float)textHeightWithString:(NSString *)text FontSize:(float)fontSize Width:(float)viewWidth {
UILabel *tempLab = [UILabel new];
[tempLab setFrame:CGRectMake(0, 0, viewWidth, 1000)];
[tempLab setText:text];
[tempLab setFont:[UIFont systemFontOfSize:fontSize]];
[tempLab setNumberOfLines:0];
[tempLab sizeToFit];
CGRect curRect = tempLab.frame;
curRect.size.width = viewWidth;
tempLab.frame = curRect;
return curRect.size.height;
}
应用
评论列表,三行一下全部展示,超过三行需要展开才能查看全文。
- (void)initCellWithObject:(id)object IndexPath:(NSIndexPath *)indexPath {
[self releaseAction];
if (object) {
_dataModel = (GAMessageModel *)object;
NSInteger tempLine = [GAPublicClass textLineWithString:_desLab.text FontSize:13.0 Width:DE_SCREENWIDTH - 74];
if (tempLine > 3) {
_funBut.hidden = NO;
if (!_dataModel.dIsShowAll) {
// 不展示
[_funBut setTitle:@"全部" forState:UIControlStateNormal];
[_desLab setNumberOfLines:3];
} else {
// 展示
[_funBut setTitle:@"收起" forState:UIControlStateNormal];
[_desLab setNumberOfLines:0];
}
} else {
[_desLab setNumberOfLines:0];
}
}
}
/// 获取固定宽度的文本有多少行
+ (NSInteger)textLineWithString:(NSString *)text FontSize:(float)fontSize Width:(float)viewWidth {
UILabel *tempLab = [UILabel new];
[tempLab setFrame:CGRectMake(0, 0, viewWidth, 1000)];
[tempLab setText:text];
[tempLab setFont:[UIFont systemFontOfSize:fontSize]];
[tempLab setNumberOfLines:0];
[tempLab sizeToFit];
CGRect curRect = tempLab.frame;
curRect.size.width = viewWidth;
tempLab.frame = curRect;
NSInteger lines = curRect.size.height / (fontSize+1);
return lines;
}
示意图