UICollectionView Scrolling to an Item

14,923

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.

Share:
14,923

Related videos on Youtube

kzia
Author by

kzia

Updated on September 16, 2022

Comments

  • kzia
    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
      micantox almost 11 years
      Does 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 to NSLog [self.collectionView numberOfItemsInSection:section]; and let us know
    • kzia
      kzia almost 11 years
      Thank 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!
    • igrek
      igrek
      did 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