How can we hide the tableHeaderView and tableFooterView?

Instead of hiding the header view you should do,

tableView.tableHeaderView = nil

And later if you want to show it then just assign it again,

tableView.tableHeaderView = tableHeaderView;

In Swift:

class myTableViewController: UITableViewController {

    @IBOutlet var tableHeaderView: UIView!

    private func toggleHeaderView() {
        if tableView.tableHeaderView == nil {
            tableView.tableHeaderView = tableHeaderView 
        } else { 
            tableView.tableHeaderView = nil 
        }
    }

}

on your Storyboard, simply drag a UIView in to the table view. It will "magically" become the table view header (if you do another one, it will become the table view footer). HOWEVER you must click on that header view, and drag the referencing outlet to the table view controller, and link it to "tableHeaderView" ... that part is not "magic".

Note that because of the "!" in the declaration, you have to remember to drag the link on Storyboard or you'll get a runtime error during testing, so that's a good thing.


If you created your view in storyboard, you can hide it temporary with

tableView.tableHeaderView?.frame = CGRect.zero

To display it again, use

tableView.tableHeaderView?.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50)


Try:

tableView.tableHeaderView?.removeFromSuperview()
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))
tableView.layoutIfNeeded()

Set an UIView with height as CGFloat.leastNonzeroMagnitude instead of '0'. This will remove the blank space appearing at the top after removing the tableViewHeader. This worked for me.