由于网络获取到的数据有一定的时间,而创建tableview一般是在获取到数据之前,在获取到数据之后要刷新tableview,那么该如何更新适配文字的cell的高度呢。
我一般用到的方法是给自定义的cell添加一个更新lable的高度的方法。先预算出文字的高度,然后reloadData tableview的时候刷新即可。同时在viewcontroller里的heightForRowAtIndexPath方法里也需要预算出cell的高度,两个高度要同时更改,具体代码如下:
给自定义cell写一个更改高度的方法:
.h
- (void)getModleWithString : (NSString *)TextStr;
.m
- (void)getModleWithString : (NSString *)TextStr{
//拿到传入的文字
self.LableText.text = TextStr;
//根据文字计算出高度,这里的宽度一定要算,如果lable两边有边距,要用屏幕的宽度减去两边的间距作为这里计算的宽度
CGRect rect = [TextStr boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 0) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
//更改table的高度
self.LableText.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, rect.size.height);
}
在ViewController中调用:
//调用cell中方法传入数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
LableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
if (cell == nil) {
cell = [[LableTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
[cell getModleWithString:self.tableArr[indexPath.row]];
}
return cell;
}
//预算出文字高度,给出tableview的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGRect rect = [self.tableArr[indexPath.row] boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 0) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
//这里要给出lable的高度 + 其他控件的高度
return rect.size.height + 10;
}
具体详细了解有demo -> cell自适应demo传送门
iOS8新特性Self Sizing Cells可以自己适配cell高度
在iOS8苹果推出一个可以自动适配cell高度的方法,很简单,用xib约束好Lable的上下左右的边距值后,不需要给高度,只需在tableview创建后写下面两句代码
self.MTableView.estimatedRowHeight = 50.0f;//预算cell的平均高度,比如有2个cell,一个高度大概有80,另一个40,那么写它们的平均值60即可
self.MTableView.rowHeight = UITableViewAutomaticDimension;//默认值
写了以上两句之后
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
这个方法可以不写,会自动根据约束边距的宽算出高度,并自动更改tableview的cell的高度。
但是这个方法只支持iOS8以上,而且听说estimatedRowHeight这个预算值,如果和某个cell的高度相差特别大,可能滑动的时候会有看见跳动的变化,所以少量的cell个数可以考虑,但是我还没有碰到跳跃的效果,具体用哪个方法,要根据实际情况大家自己选择啦。
网友评论