Alessandro Garcez
Alessandro Garcez

Reputation: 728

UICollectionView - Scrolling to first cell

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?

Upvotes: 20

Views: 38542

Answers (8)

zekel
zekel

Reputation: 9457

I found this to work reliably on all devices and correctly handle iPhone X-style safe areas.

let top = CGPoint(
  x: collectionView.contentOffset.x,
  y: collectionView.adjustedContentInset.top
)
collectionView.setContentOffset(top, animated: false)

(This scrolls vertically to the top but you could easily make it scroll to the top-left if you wanted.)

Upvotes: 0

JP Aquino
JP Aquino

Reputation: 4066

 scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: true)

Upvotes: 1

user5052831
user5052831

Reputation:

The following solution works fine for me:

UIView.animate(withDuration: 0.5, animations: {
     self.collectionView?.contentOffset.x = 0
})

It scrolls to the first item and the contentInset can be seen as well.

Upvotes: 3

Samy Nagy
Samy Nagy

Reputation: 180

if let indexPath = self.collectionView?.indexPathForItem(at: CGPoint(x: 0, y: 0)) {
            self.collectionView?.scrollToItem(at: indexPath, at: .top, animated: false)
}

Upvotes: 0

Celil Bozkurt
Celil Bozkurt

Reputation: 1783

You can use this for Objective - C

        [self.restaurantCollectionView setContentOffset:CGPointZero animated:YES];

Upvotes: 2

Jacopo Penzo
Jacopo Penzo

Reputation: 2168

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

Upvotes: 50

user6226218
user6226218

Reputation:

It might be possible to use the UIScrollView related property

collectionView.contentOffset.x = 0

Upvotes: 14

Kavita
Kavita

Reputation: 176

Default CollectionView Delgeate...

- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;

Upvotes: 0

Related Questions