iOS-谈一谈自适应Cell的高度缓存

iPhone XR:828px x 1792px

iPhone XS Max: 1242px x 2688px

iPhone X 的尺寸375ptx812pt



这里有两个能够让Cell自适应的方式

对UITableView进行设置

tableView.rowHeight =UITableViewAutomaticDimension

通过代理返回

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {

returnUITableViewAutomaticDimension;

}

结果是无论使用哪个方法、在每次Cell即将被展示的时候、都会自动调用上述的systemLayoutSizeFittingSize方法。

两个关键的步骤是:

通过cellForRowAtIndexPath对某个Cell进行配置

而我们在这一步已经将Cell的内容配置完毕了

通过[UITableView _heightForCell:atIndexPath:]计算Cell高度

而内部则调用systemLayoutSizeFittingSize获取具体的高度。

如何缓存?

经过以上两个探索、我们已经知道Cell通过systemLayoutSizeFittingSize高度、并且不会被缓存。

那么、我们需要做的就是自己计算高度、并且缓存。直接贴一下代码:

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {

BSQuestionsModel * model = _dataArray[indexPath.section];

returnmodel.cell_height?:UITableViewAutomaticDimension;

}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

BSQuestionsModel * model = _dataArray[indexPath.section];

BSQuestionsTableViewCell * cell = [BSQuestionsTableViewCell cellForTableView:tableView model:model];

//高度缓存

CGFloatheight = [cell systemLayoutSizeFittingSize:CGSizeMake(tableView.frame.size.width,0) withHorizontalFittingPriority:UILayoutPriorityRequiredverticalFittingPriority:UILayoutPriorityFittingSizeLevel].height;

model.cell_height = height;

returncell;

}

这样、cell在进行过一次高度计算之后。就不需要在计算第二次了

然后关于上面的代码有几点需要说:

为什么在cellForRowAtIndexPath里做缓存

最开始我们已经谈过了、cellForRowAtIndexPath的调用在获取自动布局的高度之前、这样也能避免重复取用对应位置的Cell。

而返回的UITableViewAutomaticDimension主要是为了怕低版本有问题(虽然我感觉应该不会)。

为什么用systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority

网上很多帖子都这样写:

[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]

但是在我这不太好用、因为我cell内部有一些优先级的设置。

所以、我干脆和系统调用的方式一样。

异步计算

是的、我们又可以异步计算了。虽然我没写、因为我现在得抓紧码页面~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容