iOS Swift的viewForHeaderInSection未被调用

21

我有一个UITableview,我想在它上面添加一个HeaderView。

然而,viewForHeaderInSection没有被调用,但是我看到titleForHeaderInSection被调用或显示。我还尝试使用自定义单元格标题,但也不起作用。

我不知道我做错了什么。

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Groceries"

    tableView.registerNib(UINib(nibName: "TransactionSpecifiedCategoriesTableViewCell", bundle: nil), forCellReuseIdentifier: "TransactionSpecifiedCategoriesTableViewCell")
    tableView.registerNib(UINib(nibName: "TransactionSpecifiedCategoriesHeaderViewCell", bundle: nil), forHeaderFooterViewReuseIdentifier: "TransactionSpecifiedCategoriesHeaderViewCell")
    tableView.tableFooterView = UIView(frame: CGRectMake(0, 0, 0, 0))
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 100))

    footerView.backgroundColor = UIColor.blackColor()

    return footerView

      //let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView
     //var headerView = UIView(frame: CGRectMake(0, 0, 100, 320))
    //headerView.backgroundColor = UIColor.blackColor()
    //        
    //return headerView
}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 200.0
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "First section header title"
}

在此输入图片描述

4个回答

29
在Swift 3中,你应该调用:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let rect = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 44)
        let footerView = UIView(frame:rect)
        footerView.backgroundColor = UIColor.clear
        return footerView
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }

4
我缺少 heightForHeaderInSection 方法。如果您只实现了视图,则该方法不会被调用。页脚也是同样的情况。 - olivaresF

27

viewForHeaderInSection方法属于UITableViewDelegate协议。因此,您必须将表格视图的delegate设置为您的视图控制器,以便获取此回调。您可能只是将tableview的dataSource设置为了其他方法被调用。


是的,你说得对。tableView.delegate = self 是有效的。谢谢你,我忘记了这一点。 - user3110353
很高兴这能帮到您。请不要忘记接受此答案。谢谢。 - croX
如果你在故事板中使用了tableView,那么你可以直接在故事板中设置委托方法。 - iDevAmit

8

在Swift 3.0中

你也可以在viewDidLoad方法中添加tableView.estimatedSectionHeaderHeight = 40,以便调用viewForHeaderInSection方法。


1

我在UITableViewController中遇到了viewForHeaderInSection没有被调用的问题,这个控制器默认是代理。后来发现

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat

阻止了viewForHeaderInSection被调用。因此,如果委托事物不起作用,您可能需要检查是否覆盖了其他部分标题方法之一。


8
仅供调试参考:对我而言情况恰恰相反。没有heightForHeaderInSection时,viewForHeaderInSection不会被调用。 - djv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接