cell高度一般分两种
一、定高
tableView.rowHeight = 80
相当于方法指定了所有cell高度都是80
对于定高cell,直接采用上面方式给定高度,不需要实现代理中 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 以节省不必要的计算和开销。
二、动态高度
代理方法实现后,上面的rowHeight的设置将会变成无效。在这个方法中,我们需要提高cell高度的计算效率,来节省时间。
- 对于计算出来的高度,没必要在进行二次计算。将他放到Model属性中缓存起来这样可以节约时间
- 使用自动布局并设置如下属性
tableView.rowHeight = .automaticDimension
tableView.estimatedRowHeight = 80.0
代理方法设置高度:func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 不要实现否则会引起程序崩溃
一般这种设置方式:需要满足:
1. 设置bottom也就是距离父视图间距,不然不会起作用
2. 自动布局:SnapKit、Masonry、系统自带的布局
Demo布局:SnapKit
//cell布局代码:SnapKit:
contentView.addSubview(mineIcon)
contentView.addSubview(mineName)
contentView.addSubview(timeName)
contentView.addSubview(statusLabel)
contentView.addSubview(problemDesc)
mineIcon.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(15)
make.height.width.equalTo(40)
make.top.equalToSuperview().offset(10)
}
mineName.snp.makeConstraints { (make) in
make.left.equalTo(mineIcon.snp.right)
.offset(6)
make.top.equalTo(mineIcon.snp.top)
.offset(6)
make.height.equalTo(18)
make.width.equalTo(120)
}
timeName.snp.makeConstraints { (make) in
make.left.equalTo(mineIcon.snp.right)
.offset(6)
make.top.equalTo(mineName.snp.bottom)
.offset(2)
make.height.equalTo(18)
make.width.equalTo(160)
}
statusLabel.snp.makeConstraints { (make) in
make.height.equalTo(20)
make.width.equalTo(80)
make.right.equalToSuperview().offset(-10)
make.centerY.equalTo(mineName)
}
problemDesc.snp.makeConstraints { (make) in
make.top.equalTo(mineIcon.snp.bottom).offset(10)
make.height.equalTo(24)
make.left.equalToSuperview().offset(15)
make.right.equalToSuperview().offset(-10)
}
let bottomView = UIView.init()
// bottomView.tag = 99999
bottomView.backgroundColor = SwiftTableViewColor
contentView.addSubview(bottomView)
bottomView.snp.makeConstraints { (make) in
make.height.equalTo(6)
make.top.equalTo(problemDesc.snp.bottom).offset(10)
make.bottom.equalToSuperview()
make.left.right.equalToSuperview()
}