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!
Here is my take on it, I think it's a lot simpler than what a glimpsed above. The main source of simplicity is that I'm not subclassing flow layout, rather rolling my own layout (much easier, if you ask me).
Please Note I am assuming you are already capable of implementing your own custom
UICollectionViewLayout
that will display cells and headers without floating implemented. Once you have that implementation written, only then will the code below make any sense. Again, this is because the OP was asking specifically about the floating headers part.a few bonuses:
note:
supplementaryLayoutAttributes
contains all header attributes without floating implementedprepareLayout
, since I do all computation upfront.shouldInvalidateLayoutForBoundsChange
to true!