UITableView 是我们在日常开发中经常会用到的控件,cell 的高度计算也一直是我们不可逃避的关键步骤,我们主要有以下两种方法做高度计算。
1:手动计算。
通过界面布局以及自己的业务需求 在数据模型层完成 整个 cell 的高度计算,并将结果存储到 对应的数据模型中,在tableView 的协议方法中返回即可。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let model = showModels[indexPath.row]
return model.cellHeight
}
//计算文本标签的size的方法:
let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying)
let strSize = string.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size
2:自动计算
我们也可以设置系统自动为我们计算cell 的高度,更方便快捷减少操作的复杂度。
tableView.rowHeight = UITableViewAutomaticDimension
或者在协议方法中设置:
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)in