tableView/collectionView复用prepareForReuse

Cell被重用如何提前知道?

可以重写cell的prepareForReuse, 官方头文件中有说明.当前已经被分配的cell如果被重用了(通常是滚动出屏幕外了),会调用cell的prepareForReuse通知cell.注意这里重写方法的时候,注意一定要调用父类方法[super prepareForReuse] .

// if the cell is reusable (has a reuse identifier), 
this is called just before the cell is returned from the table view method dequeueReusableCellWithIdentifier:.  
If you override, you MUST call super.
// 如果cell是被复用的,prepareForReuse会在tableView dequeueReusableCellWithIdentifier之前调用
// 重写此方法, 必须调用[super prepareForReuse];
- (void)prepareForReuse NS_REQUIRES_SUPER;

------------------------------
- (void)prepareForReuse {
    [super prepareForReuse];
    // ... 
    // 恢复cell的初始状态,设置image为nil或者占位图,设置默认文案,选中态恢复成默认态
    // ...
}                                                        

To avoid potential performance issues, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state.

为了避免潜在的性能问题,您应该只重置与内容无关的单元格属性,例如alpha、编辑和选择状态。

The table view's delegate in tableView(_:cellForRowAt:) should always reset all content when reusing a cell.

在重用单元格时,tableView中的表视图的委托(cellForRowAt:)应始终重置所有内容。

The table view doesn’t call this method if the cell object doesn’t have an associated reuse identifier, or if you use reconfigureRows(at:) to update the contents of an existing cell.

如果单元格对象没有关联的重用标识符,或者如果您使用reconfigureRows(at:)更新现有单元格的内容,则表视图不会调用此方法。

这个在使用cell作为网络访问的代理容器时尤其要注意,需要在这里通知取消掉前一次网络请求.不要再给这个cell设置数据了.

自定义UITableViewCell的方法有很多, 发现一些人都会遇到自己定义的cell里面图片错乱的问题. 这个问题往往是因为没有实现prepareForReuse这个方法导致的.

UITableViewCell在向下滚动时复用, 复用的cell就是滑出去的那些, 而滑出去的cell里显示的信息就在这里出现了, 解决的方法就是在UITableViewCell的子类里实现perpareForReuse方法, 把内容清空掉. 或者 在tableView:cellForRowAtIndexPath:中设置新的网络图和占位图, 覆盖掉复用池中取出的cell图片.

总结一下: 系统提供出了一个时机来重置cell的状态, 但是根本不要使用 prepareForReuse 。这个方法存在,但很少有情况下它是有用的。在 tableView:cellForRowAtIndexPath中完成所有工作, 这样更清晰, 更容易跟踪问题。

官方文档地址: Apple Developer Documentation

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值