iOS笔记之UITableView自动计算cell高度

方法一:使用系统自动计算cell高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = 
      [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return [cell.contentView systemLayoutSizeFittingSize:
      UILayoutFittingCompressedSize].height;
}

方法二:使用第三方库
下载地址:UITableView-FDTemplateLayoutCell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellReuseId = [self getReuseIdWithIndexPath:indexPath];  //获取cell id
    CGFloat height = [tableView fd_heightForCellWithIdentifier:cellReuseId cacheByIndexPath:indexPath configuration:^(id cell) {
        [self configureCell:cell indexPath:indexPath];  //对cell进行赋值
    }];
    return height;
}

tips:使用fd的时候需要注意,cell在竖直方向的约束必须要撑满
举例说明:cell里面有一个label,进行约束设置.

错误示范:

[label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.contentView);
    make.centerY.equalTo(self.contentView);  //竖直方向约束是不满的,虽然label会有一个本身的高度
}

正确做法:
法一:

[label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.contentView);
    make.centerY.equalTo(self.contentView); 
    make.top.bottom.equalTo(self.contentView);  //约束撑满竖直方向
}

法二:

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

推荐阅读更多精彩内容