Stefan Badertscher
Stefan Badertscher

Reputation: 341

How to make a sticky footer and header with a tableview?

I have a UITableView in the storyboard with also a header and a footer defined as can be seen in the picture.

screenshot

However, the header disappears when I move the cell (it seems the header is the top cell). Same thing with the footer. It appears after I have browsed through all cells. I tried to move the header and the footer outside of the Cell hierarchy. But this resulted in being not visible any more.

How can I make the header and footer sticky?

Upvotes: 0

Views: 5376

Answers (2)

FelixSFD
FelixSFD

Reputation: 6092

When using static UITableViews, you can't add custom views as header. You need to set the header and footer like this:

//Header
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    //return your custom view here
}

//Footer
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    //return your custom view here
}

You also have to specify the height of your header/footer:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    //return the height
}

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    //return the height
}

Upvotes: 0

matt
matt

Reputation: 534925

Don't confuse the section header and footer with the table header and footer.

  • The section header and footer, in a non-grouped table, are pinned to the top and bottom of the table while you scroll.

  • But the table header and footer, as you rightly say, are sort of like cells: they are before the first section and after the last section, and they scroll with the table.

If that's not what you want — that is, if there is something you want to show above the table and below the table, all the time — then you need to put them above and below the table view as completely separate views:

thing above
table
thing below

Of course, if you do that, you can't use a UITableViewController. You'll have to have a normal view controller, with the table view as an embedded view and the table view controller as a child view controller.

Upvotes: 3

Related Questions