我有一个tableview,我有20个原型单元,并且tableview的Content参数是Dynamic Prototypes

一次我只显示一个原型单元,但是由于某些奇怪的原因,cellForRowAtIndexPath被调用了两次。

我遍历了代码,仅一次调用了reloaddata。

我不知道是什么原因导致tableview两次调用cellForRowAtIndexPath!

所以我通常想知道是什么和所有可能导致tableview为同一行多次调用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()

关于ios - 是什么原因让cellForRowAtIndexPath每行多次调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48381561/

10-14 21:38
查看更多