I'm struggling to achieve a "floating section header" effect with UICollectionView. Something that's been easy enough in UITableView (default behavior for UITableViewStylePlain) seems impossible in UICollectionView without lots of hard work. Am I missing the obvious?
Apple provides no documentation on how to achieve this. It seems that one has to subclass UICollectionViewLayout and implement a custom layout just to achieve this effect. This entails quite a bit of work, implementing the following methods:
Methods to Override
Every layout object should implement the following methods:
collectionViewContentSize
layoutAttributesForElementsInRect:
layoutAttributesForItemAtIndexPath:
layoutAttributesForSupplementaryViewOfKind:atIndexPath: (if your layout supports supplementary views)
layoutAttributesForDecorationViewOfKind:atIndexPath: (if your layout supports decoration views)
shouldInvalidateLayoutForBoundsChange:
However its not clear to me how to make the supplementary view float above the cells and "stick" to the top of the view until the next section is reached. Is there a flag for this in the layout attributes?
I would have used UITableView but I need to create a rather complex hierarchy of collections which is easily achieved with a collection view.
Any guidance or sample code would be greatly appreciated!


Either implement the following delegate methods:
In your view controller that has your
:cellForItemAtIndexPathmethod (just return the correct values). Or, instead of using the delegate methods, you may also set these values directly in your layout object, e.g.[layout setItemSize:size];.Using either of these methods will enable you to set your settings in Code rather than IB as they're removed when you set a Custom Layout. Remember to add
<UICollectionViewDelegateFlowLayout>to your .h file, too!Create a new Subclass of
UICollectionViewFlowLayout, call it whatever you want, and make sure the H file has:Inside the Implementation File make sure it has the following:
Choose "Custom" in Interface Builder for the Flow Layout, choose your "YourSubclassNameHere" Class that you just created. And Run!
(Note: the code above may not respect contentInset.bottom values, or especially large or small footer objects, or collections that have 0 objects but no footer.)