maxim rad
maxim rad

Reputation: 67

scrollToItem UICollectionView error - index out of range

When I run on simulator it works ok. But when I run on physical device, I face an error - index out of range.
Code:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let index = NSIndexPath(row: 0, section: 0) as IndexPath
    resultController?.collectionView?.scrollToItem(at: index, at: .bottom, animated: true)
}

Screenshot: enter image description here

P.S : I want UICollectionView to scroll to top when I click.

Upvotes: 0

Views: 863

Answers (2)

kai
kai

Reputation: 330

I have tested your code in my project. It works fine. Please check whether your resultController?.collectionView? is right.

Upvotes: 0

nathangitter
nathangitter

Reputation: 9795

To scroll to the top of the view, use the setContentOffset method.

collectionView?.setContentOffset(CGPoint.zero, animated: true)

Your issue is caused by the collection view's automatic cell reuse, which dequeues cells when they go offscreen. This sometimes results in no cell at the first index, which is the reason for the index out of range error.

Upvotes: 1

Related Questions