我有一个表格视图,我有 20 个原型单元格,表格视图的内容参数是动态原型
有一次我只显示一个原型细胞,但由于某种奇怪的原因,cellForRowAtIndexPath被调用了两次。
我已经浏览了我的代码,我只调用了一次 reloaddata。
我无法弄清楚是什么导致表视图调用cellForRowAtIndexPath两次!
所以我通常想知道什么和所有可能导致表视图为同一行多次调用cellForRowAtIndexPath
更新:
在其中一个原型单元格中,如果单击一个按钮,那么我可能会重新加载数据,以便我可以显示其他一些原型单元格,但随后也会调用两次
但行数仍然为 1
如果你自己明确地称reloadData()
,那可以解释它。tableView
默认在UITableViewController
加载数据,因此再次显式调用它将第二次触发cellForRowAt
。您可以通过删除对reloadData()
的显式调用来轻松确认这一点 - 然后tableView
应该看起来正确,并且cellForRowAt
应该只调用一次。
我在 Playgrounds 中测试了以下最小工作示例,它只被调用了一次:
import UIKit
import PlaygroundSupport
class A: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Reload", style: .plain, target: self, action: #selector(buttonPressed))
}
@objc func buttonPressed() {
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(">>>> calling numberOfRowsInSection")
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(">>>> (indexPath)")
return UITableViewCell()
}
}
PlaygroundPage.current.liveView = UINavigationController(rootViewController: A())
因此,除非您执行其他操作,否则cellForRowAt
实际上应该每reloadData()
调用一次。
默认情况下,当初始化视图控制器以重新加载表时会有一个调用,当您添加另一个时,它是 2