kzia
kzia

Reputation: 555

UICollectionView Scrolling to an Item

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

Upvotes: 5

Views: 14984

Answers (2)

kzia
kzia

Reputation: 555

Printing numberofItemsInSection revealed that the view it used for scrolling was stale. When I used the scrollToItemAtIndexPath after refreshing the view, it worked!

Upvotes: 2

bubuxu
bubuxu

Reputation: 2197

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.

Upvotes: 12

Related Questions