UICollectionView - Scrolling to first cell

心不动则不痛 提交于 2019-12-03 10:10:38

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

It might be possible to use the UIScrollView related property

collectionView.contentOffset.x = 0

You can use this for Objective - C

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

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.

Default CollectionView Delgeate...

- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;
if let indexPath = self.collectionView?.indexPathForItem(at: CGPoint(x: 0, y: 0)) {
            self.collectionView?.scrollToItem(at: indexPath, at: .top, animated: false)
}
 scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: true)

I found 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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!