Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 960
kzia Avatar asked Jun 18 '13 14:06

kzia


2 Answers

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.

like image 71
bubuxu Avatar answered Oct 16 '22 23:10

bubuxu


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

like image 38
kzia Avatar answered Oct 17 '22 01:10

kzia