使用 UITableViewDynamicLayoutCacheHeight 实现如下的效果,Cell 自适应高度。
创建模型
我们这里创建的模型名字是 BMModel。代码如下:
创建 Cell
为了方便起见,我们这里使用 xib 创建 Cell。
创建 Cell 名字为 BMCell,如下图:
这里至关重要的就是:
- 我们的 Cell 必须使用 Autolayout ,不管你是纯代码还是Xib都可以,
- 在正常显示的时候,Cell 里必须有一个 View 的最大 Y 刚好是 Cell 需要的高度。
m 文件是如下内容:
其中使用的模型就是第一步创建的模型 BMModel。
控制器的代码
其中在返回高度的代理里面使用了如下的方法。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [tableView bm_heightWithCellClass:BMCell.class cacheByIndexPath:indexPath configuration:^(__kindof BMCell * _Nonnull cell) {
// 布局这个 Cell
cell.model = self.dataSourceArray[indexPath.row];
}];
}
在 Block 中对 Cell 继续设置相应的显示内容,就和 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
方法内部需要设置 Cell 的代码一致即可。
- 内部使用 indexPath 做了高度缓存。
- 支持屏幕旋转。