首页 > 解决方案 > 为什么不调用表视图委托方法?

问题描述

我发现我在Release配置中构建的应用程序有时会出现问题:tableView:heightForRowAt:委托方法没有被调用。

这个问题与构建有关,对于某些构建,我总是重现该问题,而对于其他一些构建,我永远无法重现它。

当问题发生时,我可以看到我的 tableView 中的行将全部 44 作为高度,并且我在方法中创建的断点tableView:heightForRowAt:永远不会被调用。

正常和错误结果的屏幕截图

在我的代码中,我尝试使用多态性来获得表视图数据源和委托方法的 2 种不同实现。这是一个简化的示例:

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var tableController: BaseTableController!

    let vm = ViewModel(sections: [...])

    override func viewDidLoad() {
        super.viewDidLoad()

        tableController = VariantATableController(viewModel: vm)
        tableView.dataSource = tableController
        tableView.delegate = tableController
    }

}
class BaseTableController: NSObject, UITableViewDataSource, UITableViewDelegate {

    let viewModel: ViewModel

    init(viewModel: ViewModel) {
        self.viewModel = viewModel
        super.init()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.sections[section].numberOfRows
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        fatalError("to be overridden")
    }    

}
class VariantATableController: BaseTableController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ACell", for: indexPath)
        let row = viewModel.sections[indexPath.section].rows[indexPath.row]
        cell.textLabel?.text = row.title
        cell.detailTextLabel?.text = row.detail
        return cell
    }

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

}
class VariantBTableController: BaseTableController {
    ...
}

标签: iosswiftuitableview

解决方案


把. tableView:heightForRowAt:_class BaseTableController: NSObject, UITableViewDataSource, UITableViewDelegate {}

UITableViewDataSource, UITableViewDelegate是必要的。


推荐阅读