Custom header view from xib for UITableView

In this step by step tutorial we will create a custom header view to use in UITableView and it will be loaded from xib file.

Creating the UITableViewHeaderFooterView class and xib

1- First of all create a new Swift file and make it subclass of UITableViewHeaderFooterView and name it “DemoHeaderView”

2- Next create an empty xib file and give it the same name as the Swift file “DemoHeaderView”

3- Add a UIView to the xib file and from its “Attributes inspector” set its “Size” property to “Freeform”.

4- Go to “Size inspector” and adjust the “Height” to whatever you want, for example 100.

5- Go to “Identity inspector” and set “Class” property to the Swift class “DemoHeaderView”, your view now should look like this

UITableViewHeaderFooterView

6- Now add another UIView as subview to the main view then inside it add UILabel

7- Press “Show the Assistant editor” to display the Swift file side by side with the xib file then control+click and drag from your label to the Swift “DemoHeaderView” class to create IBOutlet for your label and name it “lblTitle”

8- Take some time customizing the look of your header view and at the end it should be something like that

custom header view for uitableview in swift

Register and use UITableViewHeaderFooterView in UITableView

9- Now our custom header is ready but first we must register it with our table, add the following code to your view controller in viewDidLoad() function

let headerNib = UINib.init(nibName: "DemoHeaderView", bundle: Bundle.main)
tblItems.register(headerNib, forHeaderFooterViewReuseIdentifier: "DemoHeaderView")

10- Use your header view by adding the following function

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "DemoHeaderView") as! DemoHeaderView
        
        headerView.lblTitle.text = "Grocery"
        
        return headerView
}

11- Configure the header view height by adding this function

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

You are done, press run and you shall see your custom header on top of  your table view

uitableviewheaderfooterview xcode swift

You can download the complete project from this link

CustomHeaderDemo

Read also Creating custom UITableViewCell from xib in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *