2015-03-19 102 views
15

我有一个UITableview我试图在UITableview上添加HeaderViewiOS Swift viewForHeaderInSection未被调用

但是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" 
} 

enter image description here

回答

16

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

+0

是的。你是对的。 tableView.delegate =自我工作。谢谢。忘了那个。 – user3110353 2015-03-19 12:44:31

+0

很高兴这有帮助。不要忘记接受这个答案。谢谢 – croX 2015-03-19 13:14:22

+0

如果使用storyboard中的tableView,则可以从storyboard本身设置委托方法。 – iDevAmit 2016-09-27 03:10:55

0

我有这个问题viewForHeaderInSection没有在UITableViewController,这是委托默认情况下调用。原来,

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

是防止viewForHeaderInSection被调用。因此,如果委托事项不起作用,则可能需要检查是否不覆盖其他节标题方法之一。

+6

仅供尝试调试的人使用:对我而言,情况正好相反。没有'heightForHeaderInSection','viewForHeaderInSection'不会被调用。 – djv 2016-10-21 00:55:45

20

迅速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 
    } 
+2

我错过了'heightForHeaderInSection'方法。如果你只实现视图,它将不会被调用。页脚也是一样。 – OlivaresF 2017-05-02 05:03:34

1

在雨燕3.0

你也可以添加tableView.estimatedSectionHeaderHeight = 40到viewDid获得viewForHeaderInSection称为