How to create custom Header and Footer view for tableview using xib in swift?

Santosh Kumar J M
3 min readAug 5, 2020

When ever we check for tableview header and footer most answers are coded programatically but tableview headerView and footerView can be created using Nib and can be used where ever needed.

  1. Custom Header View
    let’s create a file name CustomerHeaderView subClass of UITableViewHeaderFooterView.

Now let’s create Xib file of view and name it as CustomHeaderView.

To change the height of the headerView

  • select the view in the xib file created.
  • In attributes Inspector select size and set its size to freedom
  • change the height of the view to 50.

assign the CustomerHeaderView file to xib file as shown below

take an outlet for the label

2. Custom Footer View
let’s create a file name CustomerFooterView subClass of UITableViewHeaderFooterView and repeat the above steps.

In Main class file register headerView and footerView for tableview in viewDidLoad

class ViewController: UIViewController {@IBOutlet weak var tableView: UITableView!override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "CustomHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "CustomHeaderView")tableView.register(UINib(nibName: "CustomFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: "CustomFooterView") }
}

define the viewForHeaderInSection for headerView and define viewForFooterInSection for footerView.

extension ViewController: UITableViewDataSource, UITableViewDelegate {func numberOfSections(in tableView: UITableView) -> Int {return 3}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return 2}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath)cell.textLabel?.text = "IndexPath \(indexPath.row)"return cell}func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView") as! CustomHeaderViewheaderView.sectionTitleLabel.text = "TableView Heder \(section)"return headerView}func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {return 50}func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomFooterView") as! CustomFooterViewfooterView.footerLabel.text = "TableView Footer \(section)"return footerView}func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {return 50}}

run the project and hence we are done…! you can find the project at github.

Thanks for reading.

--

--