Reset scroll on UICollectionView

I use this quite often in different parts of my app so I just extended UIScrollView so it can be used on any scroll view and scroll view subclass:

extension UIScrollView {        
    /// Sets content offset to the top.
    func resetScrollPositionToTop() {
        self.contentOffset = CGPoint(x: -contentInset.left, y: -contentInset.top)
    }
}

So whenever I need to reset the position:

self.collectionView.resetScrollPositionToTop()

You want setContentOffset:. It takes a CGPoint as and argument that you can set to what ever you want using CGPointMake, but if you wish to return to the very beginning of the collection, you can simply use CGPointZero.

[collectionView setContentOffset:CGPointZero animated:YES];

In Swift:

collectionView.setContentOffset(CGPointZero, animated: true)

If you leave the view that houses the collection view, make a change in the 2nd view controller, and need the collection view to update upon returning:

@IBAction func unwindTo_CollectionViewVC(segue: UIStoryboardSegue) {
    //Automatic table reload upon unwind
    viewDidLoad()
    collectionView.reloadData()
    collectionView.setContentOffset(CGPointZero, animated: true)
}

In my situation the unwind is great because the viewDidLoad call will update the CoreData context, the reloadData call will make sure the collectionView updates to reflect the new CoreData context, and then the contentOffset will make sure the table sets back to the top.


You can use this method to scroll to any item you want:

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