Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView scrollToItemAtIndexPath

Tags:

ios

I'm trying to scroll to a specific item in a collection view and it seems to happening properly about 90 % of the time. I basically have a collection view whose frame I change via auto layout and then I want my cell be the size of the all of the new frame, so I set a new size. When I put a breakpoint on the scrollToItemAtIndexPath, it seems when it works works the item size have taken effect, but the times it doesn't work, the cell still have the old size. How can I make sure the itemSize has changed before scrolling?

[weakSelf.view removeConstraints:@[weakSelf.verticalSpace, weakSelf.collectionViewBottomSpace, weakSelf.bottomLayoutTopCollectionView]];
[weakSelf.view addConstraints:@[weakSelf.collectionViewToTop, weakSelf.imageHeight, weakSelf.youLabelToTop]];
[UIView animateWithDuration:animated ? .5 : 0.0
                                      animations:^{
                                          [weakSelf.view layoutIfNeeded];
                                      }
                                      completion:^(BOOL finished) {
  UICollectionViewFlowLayout * layout = (UICollectionViewFlowLayout *)self.currentUserCollectionView.collectionViewLayout;

  layout.itemSize = weakSelf.currentUserCollectionView.frame.size;

  [weakSelf.currentUserCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:[self getSelectedIndex:selectItem] inSection:0]
                                         atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                                 animated:NO];
}];
like image 797
Venkat S. Rao Avatar asked Nov 06 '13 15:11

Venkat S. Rao


2 Answers

Make sure the collection view has laid out its subviews first along with the resizing of the cell before scrolling. I would suggest moving your scrolling to a place where you're sure all layouts have been completed such as:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    NSIndexPath *indexPath = // compute some index path

    [self.collectionView scrollToItemAtIndexPath:indexPath
                                atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                        animated:YES];
}
like image 52
Tim Avatar answered Dec 20 '22 05:12

Tim


Another option is to call layoutIfNeeded on the UICollectionView before you call scrollToItemAtIndexPath. That way you won't perform the scroll operation every time the parent view's subviews are laid out.

like image 22
Code Commander Avatar answered Dec 20 '22 07:12

Code Commander