UICollectionView - Scrolling to first cell

Alessandro Garcez picture Alessandro Garcez · Aug 28, 2015 · Viewed 31.3k times · Source

I'm making use of UICollectionView and I need to scroll to first cell after click in a button.

The button is located in a (big) header section in my collection view... when clicking int it, I need scroll to my first cell located bellow of this button.

I created a action of this button, but I don't know how to scroll to first UICollectionViewCell.

Can someone help me?

Answer

Jacopo Penzo picture Jacopo Penzo · Aug 28, 2015

Use this delegate method, setting the indexPath at the first position:

Swift

self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), 
                                                atScrollPosition: .Top, 
                                                        animated: true)

Swift 3

self.collectionView?.scrollToItem(at: IndexPath(row: 0, section: 0), 
                                  at: .top, 
                            animated: true)

Objective-C

[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] 
                            atScrollPosition:UICollectionViewScrollPositionTop
                                    animated:YES];

Change UICollectionViewScrollPositionTop if you want to scroll and stop at a different position