prepareForReuse 的正确使用方法是什么?

问题描述 投票:0回答:2

需要帮助了解如何在 UIKit 中使用prepareForReuse()。 文档

您应该只重置与以下内容无关的单元格属性: 内容,例如 Alpha、编辑和选择状态

但是重置单个属性(例如 isHidden)怎么样?

假设我的单元格有 2 个标签,我应该在哪里重置:

  1. 标签.文本
  2. label.numberOfLines
  3. 标签.isHidden

我的 tableView(_:cellForRowAt:) 委托具有条件逻辑来隐藏/显示每个单元格的标签。

ios swift uitableview prepareforreuse
2个回答
73
投票

tldr:使用

prepareForReuse
取消可以在下载不同的索引路径后完成的现有网络调用。对于所有其他意图和目的,只需使用
cellForRow(at:
。这有点违反苹果文档。但这就是大多数开发人员的做法,因为在两个地方都有单元配置逻辑很不方便......


Apple 文档说使用它来重置与 content 相关的属性 not。然而,根据经验,只做

cellForRow
内的所有内容可能会更容易,而不是内容。唯一真正有意义的时候是

引用Apple的文档中的

prepareForReuse

出于性能原因,您应该只重置单元格的属性 与内容无关,例如 Alpha、编辑和 选择状态。

例如如果选择了一个单元格,您只需将其设置为未选择,如果您将背景颜色更改为某种颜色,那么您只需将其重置回其默认颜色。

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

这意味着,如果您尝试设置联系人列表的个人资料图像,则不应尝试在

nil
中设置图像,您应该在
prepareforreuse
中正确设置图像,如果您没有找到任何图像image
then
将其图像设置为 cellForRowAt 或默认图像。基本上,
nil
应该控制预期/意外状态。
所以基本上以下是

建议: cellForRowAt

建议采用以下方法:

override func prepareForReuse() { super.prepareForReuse() imageView?.image = nil }

另外建议默认非内容相关项目如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.imageView?.image = image ?? defaultImage // unexpected situation is also handled. // We could also avoid coalescing the `nil` and just let it stay `nil` cell.label = yourText cell.numberOfLines = yourDesiredNumberOfLines return cell }

这样您就可以放心地假设运行时
override func prepareForReuse() { super.prepareForReuse() isHidden = false isSelected = false isHighlighted = false // Remove Subviews Or Layers That Were Added Just For This Cell }

每个单元格的布局都是完整的,您只需要担心内容即可。

这是Apple建议的方式。但说实话,我还是觉得把所有东西都倒进去比较容易

cellForRowAt

,就像Matt说的那样。干净的代码很重要,但这可能并不能真正帮助您实现这一目标。但正如

Connor所说
,唯一需要的时候是,如果您需要取消正在加载的图像。更多请参见这里 即做类似的事情:

cellForRowAt

另外在使用 RxSwift 的特殊情况下:
请参阅
此处

此处


-5
投票

override func prepareForReuse() { super.prepareForReuse() imageView.cancelImageRequest() // this should send a message to your download handler and have it cancelled. imageView.image = nil }

您可以采用更面向对象的方法,创建 UITableViewCell 的子类,并定义一个方法,如 configureCell() 来处理新出队的单元格的所有重置和值设置。

© www.soinside.com 2019 - 2024. All rights reserved.