The Hit List Diary #8 – Table Header Views

Sorry it’s been a while since my last post. Here goes:

I’ve been playing a bit lately with table header views. I don’t feel good saying this, but the documentation is a bit pathetic to be honest:

Returns an accessory view that is displayed above the table.

The default value is nil. The table header view is different from a section header.

Let’s assume you understand the basic premise and ideas of a table header. What are the interesting nuances here?

One of the major purposes of UITableView is to efficiently re-use its cells (and section headers/footers ideally), to avoid creating an excess number of views at once. When such a view is scrolled offscreen, it’s removed from hierarchy, ready for re-use as needed.

Probably because it’s not worth doing anything that special, table header views (and footers too I believe) don’t appear to go through any such special handling. The header is always present in the table at the same spot, no matter how much you scroll. This could be exploited for some interesting custom UI I reckon, but not sure how confident I feel about always relying on the behaviour!


One of the most common use cases for the table’s header view is a search bar, and this is where we come across the really interesting behaviour. It turns out UITableView has special logic built in for handling UISearchBar — niceties that other views just don’t get.

Some effort is made to avoid ever having a search bar scrolled only partially into view. If you carefully drag a search bar to be part-visible, when you let go of the screen the table dutifully scrolls the bar to fully visible, or back out of sight. A similar effect is pretty easy to create for your own views if needed by implementing:

-[UIScrollViewDelegate scrollViewWillEndDragging:withVelocity:targetContentOffset:]

Related to this, is the special handling of short tables. Normally if you have a table whose content is short enough that no scrolling is required, then an introspection of the view hierarchy will tell you that the setup is quite simple: the scroll view has a small contentSize, and so doesn’t scroll (i.e. any scrolling attempt by the user bounces back into place).

But with a search bar in place, although you never see any scroll bars, it’s still possible to scroll the table a little. You can nudge it up and down to show or hide the search bar.

It seems that the presence of the search bar makes the table change its layout a bit. Now the contentSize is bumped up to always be least the height of the scroll area, plus the search bar (giving the slight scroll ability). And then some extra work is done that I don’t know yet, to stop the scroll bars flashing into view.

© Mike Abdullah 2007-2015