Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView sticky header in swift

Tags:

I'm trying to create a sticky supplementary header, which stays on top all the time and won't response to scrolling events. The solutions I found so far still react on bounch scrolling and are fixed using a custom flowLayout, which will probably be the fix for mine issue as well.

The reason I want it this way is that the header is used on other places and should be reusable. I'm hoping this could be solved this way and I don't have to create a separated view.

As I'm doing this in Swift, it would be great to have an example in Swift.

like image 207
Antoine Avatar asked Dec 05 '14 12:12

Antoine


People also ask

What is swift UICollectionView?

An object that manages an ordered collection of data items and presents them using customizable layouts.

How do I add a header in Collectionview?

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 .


1 Answers

Simplest solution for iOS 9 + as it doesn't need of writing subclass of UICollectionViewFlowLayout.

In viewDidLoad of viewController with collectionView use following code:

let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout // casting is required because UICollectionViewLayout doesn't offer header pin. Its feature of UICollectionViewFlowLayout
layout?.sectionHeadersPinToVisibleBounds = true

It is hinted by @Antoine also.

like image 82
Bibek Avatar answered Oct 09 '22 08:10

Bibek