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!
There are no section headers in the UICollectionView. So for your first task, you'll add a new section header using the search text as the section title. To display this section header, you'll use UICollectionReusableView .
Use Supplementary View to Add Header and Footer in UICollectionView.
A layout object that organizes items into a grid with optional header and footer views for each section.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With