tableView的cell自适应高度 SnapKit

1.tableview必须设置预估行高和自动计算高度

        // 自动计算行高
        tableView.rowHeight = UITableView.automaticDimension
        // 设置预估行高, 必须要写, 否则打印垃圾log日志, 提示约束冲突
        tableView.estimatedRowHeight = 176.5

不要设置代理里的下面这个方法

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

}

 

 

2.cell 中的所有元素必须放到 contentView 中

        contentView.addSubview(modeContentLabel)

 

3.cell 中的最后一个元素必须添加底部与 contentView 的约束,为了统一处理,我设置一个 snpline 作为约束的底部基准,snpline当做最后一个视图 statusLabel 和 contentView 之间的纽带。可变长度控件约束不设置高度即可。

    private let snpline = UIView().then {
        $0.backgroundColor = UIColor.red
    }

 

contentView.addSubview(snpline)

 

        snpline.snp.makeConstraints { maker in
            maker.top.equalTo(statusLabel.snp.bottom).offset(0)
            maker.left.equalTo(0)
            maker.right.equalTo(0)
            maker.bottom.equalTo(contentView).offset(-16)
            
        }

 

扩展:

如果有的 section 需要固定行高,有的 section 需要自适应高度

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 93
        }
        if indexPath.section == 1 {
            return UITableView.automaticDimension
        }
        
        return 240
    }

 

posted @ 2022-12-08 17:31  黄增松  阅读(512)  评论(0编辑  收藏  举报