UITableViewCell重用及优化注意点

在UITableView应用中,使用UITableViewCell重用机制是为了优化滚动性能,避免频繁创建和销毁cell导致的性能问题。重用机制给用户带来了更丝滑的体验。

UITableView使用重用机制只会创建一屏幕多一的UITableViewCell;每当cell滑出屏幕时就会把滑出屏幕的cell放到重用池中,当一个cell将要滑到屏幕上时就回到重用池中取相同标识的cell,当重用池中不存在此表示的cell时就会创建一个新的cell;这一过程极大的减少了内存开销。

在UITableView的回调方法中有两个主要的涉及到内存开销的方法:tableView:cellForRowAtIndexPath:和tableView:heightForRowAtIndexPath:

对于UITableView的cell使用是先确认每个cell的位置再去创建这个cell或到重用池中去吃对应的cell放到对应的位置上。也就是先调用tableView:heightForRowAtIndexPath:在调用tableView:cellForRowAtIndexPath:

Object-C:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString * identifer = @"cell";

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];

   }

    return cell;

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

   // UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    return 270;

}

Swift

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

                

        var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")

        PRLog(cell)

        if cell == nil {

           cell = UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell")

        }

       return cell!

    }

       

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

       return 270

    }

注意问题:

1、对于数据量很大且数据所显示的高度不同时(高度需要计算),上述方法将会有很严重的卡顿。

解决方法:

  • 在数据源中先把每行要设置的高度计算好,并缓存下来。显示时直接调用。
  • 尽量减少cell中图层叠加数量
  • 也可以尝试在定义的cell中使用draw方法,在其中异步绘制视图显示

2、当每次cell都创建很多才能进入重用机制,这是有可能cell的高度设置有问题

解决方法:

  • 可以尝试设置tableView的estimatedRowHeight和rowHeight属性,使得tableView在初始化时就能更快地进入重用cell的状态
tableView.estimatedRowHeight = 270

tableView.rowHeight = UITableView.automaticDimension

  • 如果数据量大且cell的高度不一致可以尝试手动管理cell重用

3、iOS 13中UITableView的新创建的cell要比其他版本数量多

(iOS 13中重用机制工作原理与以前版本略有不同,表现为在滚动时,并不会立即重用cell,直到滚动到某个位置,通常是当滚动到顶部或者底部时,才会开始重用cell。这是为了优化滚动性能,避免频繁创建和销毁cell导致的性能问题)

解决方法: 检查cell的设置高

4、在创建cell中相同类型cell的重用标识identifer要相同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值