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!
In iOS9, Apple was kind enough to add a simple property in UICollectionViewFlowLayout
called sectionHeadersPinToVisibleBounds
.
With this, you can make the headers float like that in table views.
let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
super.init(collectionViewLayout: layout)