UICollectionView Scrolling to an Item
Solution 1
Printing numberofItemsInSection revealed that the view it used for scrolling was stale. When I used the scrollToItemAtIndexPath after refreshing the view, it worked!
Solution 2
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.
Related videos on Youtube
kzia
Updated on September 16, 2022Comments
-
kzia over 1 year
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
-
micantox almost 11 yearsDoes it print the index path you're trying to reach in the error message? If it does, and it is, let's say,
[section, row]
. Try toNSLog
[self.collectionView numberOfItemsInSection:section];
and let us know -
kzia almost 11 yearsThank you micantox. Printing numberofItemsInSection revealed that the view it used for scrolling was stale. When I used the scrollToItemAtIndexPath after refreshing the view, it worked!
-
igrekdid you forget to put a dot? i.e "[self.collectionView scroll..." not "[self collectionView scroll..."(please note a dot between self and collectionView)? Looks like the error message states exactly this problem
-