iOS Swift viewForHeaderInSection未被调用

use*_*353 18 uitableview xib ios swift

我有一个UITableview我试图添加HeaderView到我的UITableview.

但是没有调用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"
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

kar*_*yan 24

快速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
    }
Run Code Online (Sandbox Code Playgroud)

  • 我错过了`heightForHeaderInSection`方法.如果仅实现视图,则不会调用它.页脚也是如此. (3认同)

cro*_*roX 19

viewForHeaderInSection方法属于UITableViewDelegate协议.因此delegate,您必须将表视图设置为视图控制器才能获得此回调.您可能只是设置了tableview,dataSource因为您调用了其他方法.


Cra*_*g P 6

在Swift 3.0中

您还可以将tableView.estimatedSectionHeaderHeight = 40添加到viewDid中,以获取调用的viewForHeaderInSection