目录
- 前言
- 使用步骤
-
demo链接
一、前言
iOS8 以后苹果推荐的使用 UITableView 的属性 estimatedRowHeight 和 rowHeight = UITableView.automaticDimension 来做 UITableViewCell 的自动适配行高的功能。
当然你也可以重写 UITableViewDelegate 的两个代理方法来实现
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(7.0));
注⚠️:通过属性实现自动适配行高 和 通过代理实现自动适配行高 最好选择其一,或者可能出现这样或那样的问题。
二、使用步骤
(1)设置 UITableView 属性 或 代理;
- 设置
UITableView属性
tableView.rowHeight = UITableView.automaticDimension
// estimatedRowHeight一般设置为TableViewCellView的默认高度
tableView.estimatedRowHeight = 300.0
- 设置
UITableView的代理
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 300
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
(2)在 cell 的 layoutSubviews 方法中布局子控件;
注⚠️:针对 cell 子控件的布局阐述:
- 只对需要自适应高度的
UILabel上下左右进行限制就可以了,不要对高度和宽度做限定; - 除了需要自适应高度的
UILabel,其他的子控件正常布局就可以了;
(3)给 cell 赋值完成之后,调用 layoutIfNeeded 方法;
注⚠️:当 cell 调用 layoutIfNeeded 方法后,会立即调用 layoutSubviews 方法去布局 cell 的子控件。
三、demo 链接
四、Author
如果你有什么建议,可以关注我的公众号:iOS开发者进阶,直接留言,留言必回。









网友评论