UITabelView的Cell自适应高度
Posted 偶阵雨ss33
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UITabelView的Cell自适应高度相关的知识,希望对你有一定的参考价值。
http://www.jianshu.com/p/83e72f90d7c1
思路:因为cell高度不固定,需要动态赋值,所以用了最常见的cell内有一个model,model内有cellHeight的方式,在cell的model的set方法中给model的cellHeght赋值。
cell.m (重写model属性的set方法)
-(void)setBaikeModel:(Model *)baikeModel{
self.titleLabel.text = baikeModel.title;
self.titleLabelHeightConstraint.constant = baikeModel.cellHeight;
}
model.m (重写title属性的set方法)
-(void)setTitle:(NSString *)title{
_title = title;
//根据后台数据,动态计算cell高度
CGFloat height = [title heightWithFont: [JYEToolModel jyeFontWithName:@"PingFangSC-Regular" size:16] withinWidth:ScreenWidth - 30];
_cellHeight = height;
}
VC.m
需要注意cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
Model *baikeModel = [self.contentArray objectAtIndex:indexPath.row];
return baikeModel.cellHeight + 12+11+20;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 70;
}
补充小工具:
#pragma mark -根据宽度,字号来计算字符串的高度
- (float) heightWithFont: (UIFont *) font withinWidth: (float) width{
CGRect textRect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:font}
context:nil];
return ceil(textRect.size.height);
}
#pragma mark -根据字号来计算字符串的宽度
- (float) widthWithFont: (UIFont *) font{
CGRect textRect = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, font.pointSize) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:font}
context:nil];
return ceil(textRect.size.width);
}
#pragma mark -根据字符串的实际高度、行间距来计算新的字符串的高度
-(float) realHeightWithDefaultHeight:(float)defaultHeight withRowSpacing:(float)rowSpacing withFont:(UIFont *)font{
CGFloat oneRowHeight = [@"test" sizeWithAttributes:@{NSFontAttributeName:font}].height;
CGFloat rows = defaultHeight/oneRowHeight;
CGFloat realHeight = defaultHeight +(rows - 1)* rowSpacing;
return realHeight;
}
#import "JYEToolModel.h"
@implementation JYEToolModel
/*
* 自定义字号大小
*/
+(UIFont *)jyeFontWithName:(NSString *)name size:(CGFloat)size{
UIFont * font = nil;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9){
font = [UIFont fontWithName:name size:size];
}else{
if([name rangeOfString:@"Medium"].location == NSNotFound){
font = [UIFont systemFontOfSize:size];
}else{
font = [UIFont boldSystemFontOfSize:size];
}
}
return font;
}
@end
以上是关于UITabelView的Cell自适应高度的主要内容,如果未能解决你的问题,请参考以下文章