How to set a custom cell as header or footer of UITableView

Byte picture Byte · Jul 1, 2016 · Viewed 15.6k times · Source

I am using Xib files instead of storyboard. I have created a table view with some dummy data. Its working fine, Now I have created a custom cell with some labels and textFields. How can I use it as header or footer of UITableView ?

Answer

Tushar Korde picture Tushar Korde · Sep 26, 2016

The answer is actually pretty simple. In viewForHeaderInSection() create cell object as you do in cellForRowAtIndexPath() and return it.

Here is sample code.

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") as! YourTableViewCell
    return cell
}

You can set height for header as:

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

Update for Swift 4.2

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! YourTableViewCell
    return cell
}

and

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