关于 tableViewcell 的高度计算

前言:tableViewcell 如果使用高度自动计算虽然方便 但是性能并不是最好的.现在说一下在 cell 创建出来之前提前计算高度.

在 cell 的.h 里面声明这个方法
- (CGFloat)getMaxY;
.m 里面实现
- (CGFloat)getMaxY{
    [self layoutIfNeeded];
    //返回最后一个控件的最大y 值
    return CGRectGetMaxY(self.expendBtn.frame) + margin;
}

在 controller 里实现 tableView 的这个代理

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   ARBookDetailIntroducCell *cell = [[ARBookDetailIntroducCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:nil];
    cell.introduction = self.model.introduction;
    NSLog(@"%.2f",[cell bookDetailIntroducCellgetMaxY]);
   //这样   我们的 cell 高度就计算出来了
  //可以将这个值 缓存起来  这样就不用每次都计算了  比如放到 model 里面 rowHeight
    return [cell bookDetailIntroducCellgetMaxY];
}

当然有个注意点

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

使用这个方法 生成的 cell 不管怎样 cell 的 bouns 都是 {(0,0),(320,44)};
如果 cell 中有 Label 是自动适应行数的 会有一些问题

这是我一个 demo 里面写的 label
 [IntroductionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(margin);
        // make.right.offset(-margin);  这是我原来写的布局  
        make.width.offset(ScreenWidth - 2 *margin);
    }];

为什么没有使用注释掉的部分 是因为用于计算的 cell 没有最终去显示,所以 它的宽度只有320
而我正式使用的 cell 最终宽度会达到我的 tableView 的宽度(比如 我的是414).
会导致我们的 label 得到的高度不一样 所以一开始 就给它设置成了 我屏幕的宽度减去两个margin 这样计算的高度就会是一样啦.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容