I am trying to memorize an index for an item (indexPath.item) in a UICollectionView and at a later time, after the view is replaced and then restored, to scroll to that memorized item.
When memorizing the item, indexPath, and indexPath.item are:
indexPath is: <NSIndexPath 0x1d87b380> 2 indexes [0, 32]
indexPath.item is: 32
When recalculating the indexPath later for that item, indexPath, and indexPath.item are:
indexPath is: <NSIndexPath 0x1d8877b0> 2 indexes [0, 32]
item is: 32
I try to scroll to the memorized location by using:
NSIndexPath *iPath = [NSIndexPath indexPathForItem:i inSection:0];
[self collectionView scrollToItemAtIndexPath:iPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
I receive an error:
attempt to scroll to invalid index path
Do you call [self.collectionView reloadData];
before trying to scroll to the indexPath?
If you want to relocate the indexPath when the reloadData finishes, place the code in a block like this:
[UIView animateWithDuration:0
animations: ^{ [self.collectionView reloadData]; }
completion:^(BOOL finished) {
NSIndexPath *iPath = [NSIndexPath indexPathForItem:i inSection:0];
[self collectionView scrollToItemAtIndexPath:iPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
}];
Before calling scrollToItemAtIndexPath
, you could also check the number of items in section to make sure i
is valid, or you still will get the same error.
Printing numberofItemsInSection revealed that the view it used for scrolling was stale. When I used the scrollToItemAtIndexPath after refreshing the view, it worked!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With