UICollectionView scrollToItemAtIndexPath

我试图滚动到收集视图中的特定项目,似乎90%的时间正确地发生。 我基本上有一个集合视图,其框架通过自动布局进行更改,然后我希望我的单元格是所有新框架的大小,所以我设置了一个新的大小。 当我在scrollToItemAtIndexPath上放置一个断点时,似乎在工作时,项目大小已经生效,但是它不工作的时间,单元仍然具有旧的大小。 如何确保itemSize在滚动之前已经更改?

[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]; }]; 

确保collections视图已经在滚动之前首先布置了子视图以及单元格的大小调整。 我build议您将滚动移动到您确定所有布局已完成的位置,例如:

 - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; NSIndexPath *indexPath = // compute some index path [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES]; } 

另一个选项是在调用scrollToItemAtIndexPath之前调用UICollectionView layoutIfNeeded 。 这样,每当父视图的子视图布局时,就不会执行滚动操作。