How to display custom footer view in table?

Krutika Sonawala picture Krutika Sonawala · Aug 31, 2018 · Viewed 7.4k times · Source

I have created a UIview class Xib to display it in footer view of my table.FooterView

import UIKit

/// This class is to display footer view in a settings table view
class FooterView: UIView {
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

I'm displaying it as below:

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let view = FooterView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 140))
    return view
}

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

What's wrong with this? I'm not able to see the footer view and getting so much space between the tableview rows.

enter image description here

Answer

Nikunj Kumbhani picture Nikunj Kumbhani · Aug 31, 2018

Using StoryBoard

In UITableView You can drag UIView, it will set as FooterView if you have more then 0 prototype cell. After Drag you can see it in tableview hierarchy as subview. Now, you can add UILabel UIButton or any component on that View, adjust the height, etc. You can also set IBAction into ViewController Class File.

Programmatically

let customView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
customView.backgroundColor = UIColor.red
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.setTitle("Submit", for: .normal)
customView.addSubview(button)

//Add that view in Table Footer View.
tableView.tableFooterView = customView // Here you can also use your xib View.

By using XIB

class MyClass: UIView {

    class func instanceFromNib() -> UIView {
        return UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
}

Initialise the view and use it like below

let FooterView = MyClass.instanceFromNib()
tableView.tableFooterView = FooterView

enter image description here

Output:

enter image description here