要运行示例项目,先克隆仓库,然后在 Example 目录中运行 pod install
。
pod 项目可以分为两个部分,单元格高度计算和缓存。您可以根据需要使用两个或其中一个。
高度缓存使用
1.1 基于位置的缓存
- (void)buildHeightCacheAtIndexPathsIfNeeded:(nullable NSArray<NSIndexPath *> *)indexPaths;
- (BOOL)hasCachedHeightAtIndexPath:(nonnull NSIndexPath *)indexPath;
- (void)cacheHeightForIndexPath:(nonnull NSIndexPath *)indexPath height:(CGFloat)height;
- (CGFloat)cachedHeightAtIndexPath:(nonnull NSIndexPath *)indexPath;
1.2 基于内容的缓存
- (CGFloat)cachedHeightWithReuseIdentifier:(nonnull NSString *)reuseIdentifer
modelKey:(nonnull id)modelKey
heightAffectedProperties:(nullable NSArray<id> *)properties;
- (void)cacheHeightForReuseIdentifier:(nonnull NSString *)reuseIdentifer
modelKey:(nonnull id)modelKey
heightAffectedProperties:(nullable NSArray<id> *)properties
height:(CGFloat)height;
- (BOOL)hasCachedHeightForReuseIdentifier:(nonnull NSString *)reuseIdentifer
modelKey:(nonnull id)modelKey
heightAffectedProperties:(nullable NSArray<id> *)properties;
高度计算使用
2.1 非缓存自动高度(始终不缓存单元格高度)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [tableView TL_autoHeightForCellWithReuseIdentifer:NSStringFromClass([TestTableViewCell class]) configuration:^(TestTableViewCell *cell) {
cell.model = self.models[indexPath.row];
}];
}
2.2 基于位置的缓存自动高度(根据索引路径缓存单元格高度)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [tableView TL_autoHeightForCellWithReuseIdentifer:NSStringFromClass([TestTableViewCell class])
indexPath:indexPath
configuration:^(TestTableViewCell * cell) {
cell.model = self.models[indexPath.row];
}];
}
2.3 基于内容的缓存自动高度(根据提供的模型键和高度受影响属性缓存单元格高度)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [tableView TL_autoHeightForCellWithReuseIdentifer:NSStringFromClass([TestTableViewCell class])
modelKey:@(self.models[indexPath.row].modelId)
heightAffectedProperties:@[self.models[indexPath.row].title, self.models[indexPath.row].content]
configuration:^(TestTableViewCell *cell) {
cell.model = self.models[indexPath.row];
}];
}
2.4 固定高度单元格高度(计算单元格高度,并且单元格高度只计算一次)。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [tableView TL_fixedHeightForCellWithReuseIdentifer:NSStringFromClass([TestTableViewCell class])
configuration:^(TestTableViewCell *cell) {
cell.model = self.models[indexPath.row];
}];
}
对于自动计算单元格高度,UITableViewCell 应使用自动布局或覆盖 UIView 方法的 - (CGSize)sizeThatFits:(CGSize)size
。提供的标识符应与单元格的 reusableIdentifer 相同(不能为空)。
TLCachedAutoHeightCell 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile
pod "TLCachedAutoHeightCell"
ToccaLee, [email protected]
TLCachedAutoHeightCell 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。