UITableViewCell的高度缓存

本文介绍如何使UITableViewCell高度自适应,并通过缓存机制提高效率。主要涉及UITableView的设置和代理方法,以及如何利用systemLayoutSizeFittingSize方法获取并缓存Cell的高度。
让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高度缓存的目的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值