iOS点点滴滴iOS学习开发手机移动程序开发

UITableViewCell高度自适应

2020-01-03  本文已影响0人  __Mr_Xie__

目录

一、前言

iOS8 以后苹果推荐的使用 UITableView 的属性 estimatedRowHeightrowHeight = 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 属性 代理;

tableView.rowHeight = UITableView.automaticDimension
// estimatedRowHeight一般设置为TableViewCellView的默认高度
tableView.estimatedRowHeight = 300.0
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
     return 300
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return UITableView.automaticDimension
}

(2)在 celllayoutSubviews 方法中布局子控件;

注⚠️:针对 cell 子控件的布局阐述:

(3)给 cell 赋值完成之后,调用 layoutIfNeeded 方法;

注⚠️:当 cell 调用 layoutIfNeeded 方法后,会立即调用 layoutSubviews 方法去布局 cell 的子控件。

三、demo 链接

demo

四、Author

如果你有什么建议,可以关注我的公众号:iOS开发者进阶,直接留言,留言必回。

上一篇下一篇

猜你喜欢

热点阅读