为什么覆盖tableView(:viewForHeaderInSection :)会改变结果

时间:2018-11-07 17:38:19

标签: ios uitableview

我有一个没有标题的表视图的简单实现。这就是我要追求的结果。

class NavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.pushViewController(MyTable(style: .grouped), animated: false)
    }
}

class MyTable: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        assert(false)
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

table view with no header

请注意,我有一个viewForHeaderInSection的替代项,因为我给出的高度基本上为零,所以它从未被调用。

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    assert(false)
}

当我删除上面函数的定义时,我得到了不同的结果。为什么会发生这种情况,并且有一种方法可以得到相同的结果而不覆盖此方法?

table view with header

2 个答案:

答案 0 :(得分:1)

如果UITableView的委托实现了tableView(_:viewForHeaderInSection:),则调用UITableView会从假设您希望在节标题中提供 titles 到认为您希望在节中具有 views 标头。进行该切换后,它将检查委托人的tableView(_:heightForHeaderInSection:) -由于您(有效)返回零,因此我猜想可以在不向委托人查询实际视图的情况下布置表视图。

请记住,进行此切换不必涉及调用view-for-header方法。 UITableView可以检查其委托是否为该方法实现ObjC选择器,而无需实际调用它,并相应地更改其行为。这就是您的主张永不触发的原因。

答案 1 :(得分:0)

如果您没有该函数附带的override关键字,则编译器实际上会引发错误。

  

覆盖声明需要一个'override'关键字

Error when not using override

相关问题