How to create a 'sticky' footer for a UICollectionView?

toblerpwn picture toblerpwn · Jan 19, 2013 · Viewed 10.8k times · Source

What is the best method to provide a footer for a UICollectionView that "sticks" to the bottom of the screen bounds on a given page? Assume the UICollectionView is full screen and only has one section.

Currently I am providing a UICollectionReusableView object in collectionView:viewForSupplementaryElementOfKind:atIndexPath:, but (as one might expect) when the content of my collection exceeds this screen's bounds, the footer is pushed off-screen.

I'm guessing the key is a Decoration View - but I can't find any good code (non-IB) examples on how these work, and Apple's documentation is in my opinion unclear on this particular subject.

Update re: Decoration Views

After building out and experimenting with a Decoration View (using this tutorial), I hit some limitations - namely that there aren't really any callbacks between the Decoration View object and your UICollectionViewController controller object (the Decoration View is managed by a UICollectionViewLayout object, not the UICollectionViewController object). It seems Apple was very serious about Decoration Views being limited to visual adornments, and not data-driven (although you could obviously hack around this).

So, the "right" solution still eludes me, but in the mean time I just created a static UIView object and am just managing that from my UICollectionViewController object. It works OK, but feels wrong.

Update re: Sticky HEADERS

Over the last few months, I've worked on similar issues across various projects, and did recently find a solution for sticky HEADERS. I assume the same would apply to footers, but I haven't tested it.

Details about headers here:

How to make Supplementary View float in UICollectionView as Section Headers do in UITableView plain style

The implementation is pretty heavy, but it seems to work well in most circumstances.

If there is no further activity on this question soon, I will close as a duplicate and point to the article above.

Answer

Derrick Hathaway picture Derrick Hathaway · Jun 4, 2013

Basically what you need to do is provide a custom UICollectionViewLayout subclass that invalidates itself when the bounds change (when the view scrolls the bounds change). And then provides UICollectionViewLayoutAttributes for the supplementary view where the center is updated to hug the current bounds of the collection view (top, bottom, left, right, whatever).

I added project on github that demonstrates this strategy.

UPDATE: as of iOS 9, UICollectionViewFlowLayout has two very handy properties that simplify this task drastically. See sectionHeadersPinToVisibleBounds and sectionFootersPinToVisibleBounds.