UICollectionView with sticky headers

For my latest app I wanted UICollectionView to behave like a UITableView in respect to its headers sticking to the top of the screen. Well, actually I wanted my collection view to scroll horizontally and therefor have the header cells stick to the left side of the screen.

I found a simple tutorial on stackoverflow and here how to create a UICollectionView with sticky headers. I don’t which copied from which so I’m just going to link them both.

If you want to have your collection view scroll vertically, you just have to subclass UICollectionViewFlowLayout and implement –(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect; the way it is described on SO and you are done. Since I wanted my view to scroll horizontally I had to tweak it a little bit.

It is still pretty simple – near the end of the method you just implemented (or dare I say copied?) you just exchange the following code. (Or you can just skip ahead to my gist and look at the whole file)


With this code:

Now your collection view should work as intended (if you set its layout to custom and chose the UICollectionViewFlowLayout subclass you just created)

Drawbacks of sticky headers

When scrolling an item into view using -(void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition; you cant use the positioning identifiers UICollectionViewScrollPositionTop when scrolling vertically or UICollectionViewScrollPositionLeft when scrolling horizontally because then the item you are scrolling to will be put behind the sticky headers. That sucks, but can be avoided by simply choosing another position for the element.

I briefly attempted to solve this problem but did not get the wanted results in my self-appointed timeframe, so for now it stays the way it is. Also for me it’s not a show-stopper since I want my elements to be centered horizontally (scroll position UICollectionViewScrollPositionCenteredHorizontally).

If you enjoyed this post, how about leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

One thought on “UICollectionView with sticky headers

Leave a Reply

Your email address will not be published.