Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 520
100grams Avatar asked Nov 22 '12 11:11

100grams


People also ask

How to add section header in collection view?

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 .

What is the purpose of supplementary views when used with a UICollectionView?

Use Supplementary View to Add Header and Footer in UICollectionView.

What is UICollectionView flow layout?

A layout object that organizes items into a grid with optional header and footer views for each section.


1 Answers

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) 
like image 188
ipraba Avatar answered Sep 20 '22 14:09

ipraba