Reputation: 67
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)
}
P.S : I want UICollectionView
to scroll to top when I click.
Upvotes: 0
Views: 863
Reputation: 330
I have tested your code in my project. It works fine. Please check whether your resultController?.collectionView?
is right.
Upvotes: 0
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