iOS开发——UITableView优化之缓存cell高度

为什么要缓存高度?

因为当tableView滚动时会不停的回调- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;这个代理方法,当cell的高度需自适应内容时,就意味着每次回调这个方法时都要计算高度,而计算是要花时间了,在用户体验上的体现就是卡顿。为了避免重复且无意义的计算cell高度,缓存高度就显得尤为重要了。

怎样缓存?

缓存高度需要一个可变数组,每当回调- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;这个方法时,我们先去这个数组里去取,如果有,就直接拿出来,如果没有,就计算高度,并且放进数组。

代码讲解

  • 这是我们用来装缓存高度的可变数组
    /** 缓存cell高度的数组 */
    @property (nonatomic,strong) NSMutableArray *heightArray;
  • 注意懒加载
    - (NSMutableArray *)heightArray{
      if (_heightArray == nil) {
          _heightArray = [NSMutableArray array];
      }
      return _heightArray;
    }
  • 缓存高度

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
      CGFloat height;
    
      if (self.heightArray.count > indexPath.row) {
          // 如果有缓存的高度,取出缓存高度
          height = [self.heightArray[indexPath.row] floatValue];;
      }else{
          // 无缓存高度,计算高度,并加入数组
    
          // 高度根据评论内容多少自适应
          CQGoodsCommentModel *model = self.dataArray[indexPath.row];
          // 列寬
          CGFloat contentWidth = screenWidth-20;
          // 用何種字體進行顯示
          UIFont *font = [UIFont systemFontOfSize:13];
          // 计算size
          CGSize size = [model.comment_content sizeWithFont:font constrainedToSize:CGSizeMake(contentWidth, 1000) lineBreakMode:UILineBreakModeWordWrap];
    
          // 這裏返回需要的高度
          height = size.height+60;
          // 加入数组
          [self.heightArray addObject:[NSNumber numberWithDouble:height]];
      }
      return height;
    }
  • 刷新tableView时记得清空高度缓存数组
    // 设置表头
      self.contentTableView.header = [CQHeader headerWithRefreshingBlock:^{
          _page = 1;
          [self.heightArray removeAllObjects];
          [self getDataIsRefresh:YES];
      }];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值