程序员2017,我们一起努力iOS 开发

UITableViewCell的高度缓存

2018-11-08  本文已影响17人  否极泰来_L
让UITableViewCell高度自适应的方法有两种

1、对UITableView进行设置

tableView.rowHeight = UITableViewAutomaticDimension;

2、通过代理返回

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

使用自适应高度时,在Cell每次即将被展示出来的时候都会调用Cell中的 ⬇️方法进行计算。

- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority verticalFittingPriority:(UILayoutPriority)verticalFittingPriority NS_AVAILABLE_IOS(8_0);

但是系统计算行高后并没有进行缓存,每次Cell即将出现的时候都会重新计算一遍高度。

缓存高度

我们知道Cell通过systemLayoutSizeFittingSize...方法获取高度。

那么我们需要做的就是调用Cell的systemLayoutSizeFittingSize...方法获取到高度,然后存储到Cell对应的数据源中。

在返回Cell高度的代理方法heightForRowAtIndexPath中判断数据源中是否有高度,如果有高度直接返回,如果没有高度返回自适应高度枚举UITableViewAutomaticDimension


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HLCellHeightCacheModel *model = self.datas[indexPath.row];
    return model.cellHeight ? : UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HLCellHeightCacheModel *model = self.datas[indexPath.row];

    HLCellHeightCacheCell *cell = [HLCellHeightCacheCell cellWithTableView:tableView identifier:@"HLCellHeightCacheCellID"];
    [cell updateView:model];
    
    if (!model.cellHeight) {
        //    高度缓存
        CGFloat height = [cell systemLayoutSizeFittingSize:CGSizeMake(tableView.frame.size.width, 0) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel].height;
        model.cellHeight = height;
    }
    return cell;
}
这样就做到了Cell高度缓存的目的
上一篇下一篇

猜你喜欢

热点阅读