Start UICollectionView at a specific indexpath

Zack picture Zack · Aug 6, 2013 · Viewed 32.3k times · Source

I currently have a collection view that does horizontal paging where each cell is fullscreen. What I want to do is for the collectionview to start at a specific index when it shows.

Right now I'm using scrollToItemAtIndexPath:atScrollPosition:animated: with animated set to NO but that still loads the first index first before it can scroll to the specific item. It also seems I can only use this method in ViewDidAppear so it shows the first cell and then blinks to the cell that I want to show. I hide this by hiding the collection view until the scroll has finished but it doesn't seem ideal.

Is there any better way to do this other than the way I described it?

Thanks!

Answer

sschale picture sschale · Feb 28, 2016

So I solved this a different way, using the UICollectionViewDelegate method and a one-off Bool:

Swift 2:

var onceOnly = false

internal func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    if !onceOnly {
        let indexToScrollTo = NSIndexPath(forRow: row, inSection: section)
        self.problemListCollectionView.scrollToItemAtIndexPath(indexToScrollTo, atScrollPosition: .Left, animated: false)
        onceOnly = true
    }

}

Swift 3:

  var onceOnly = false

  internal func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if !onceOnly {
      let indexToScrollTo = IndexPath(item: row, section: section)
      self.problemListCollectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
      onceOnly = true
    }
  }

This code is executed before any animation occurs (so it really loads to this point), which is better than attempting to call in viewDidAppear, and I didn't have success with it in viewWillAppear.