2

I have created a UIView on my storyboard and I want to use this view for the header of my UITableView. I have gave an identifier on storyboard for this view and in viewForHeaderInSection class I dequeue this identifier as shown below. However, whenever I reload the table and I found the headerCell is a new instance. It is not reused in this case.

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! UserHomeHeaderCell

I have tried to register this class on viewDidLoad() method as below:

tableView.registerClass(UserHomeHeaderCell.classForCoder, forCellReuseIdentifier: "HeaderCell")

But all the cell's content which are linked with storyboard are nil. How should I reuse this header?

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • I think your best option is to move the header view into it's own separate .xib file and load it from there. – Danny Bravo May 10 '16 at 09:21
  • Another approach is mentioned in the below link. [SO link](http://stackoverflow.com/questions/9219234/how-to-implement-custom-table-view-section-headers-and-footers-with-storyboard) The key is 'use a prototype cell as your section header and / or footer.' but this is a hack with prototype cells. Best approach is to use a Nib. – Sanu S May 10 '16 at 09:26
  • http://samwize.com/2015/11/06/guide-to-customizing-uitableview-section-header-footer/ refer this link.. it uses reusable header view.. – Rohit Pradhan May 10 '16 at 09:35

2 Answers2

-1

You have to register nib in the ViewDidLoad()

tableView.registerNib(UINib(nibName: "UserHomeHeaderCell" , bundle: nil), forHeaderFooterViewReuseIdentifier: HeaderCell)
Sucharu Hasija
  • 1,096
  • 11
  • 23
-1

try this:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! UserHomeHeaderCell
    return headerCell.contentView
}
Adam Smaka
  • 5,977
  • 3
  • 50
  • 55