将 scrollToItemAtIndexPath 方法写在 viewDidLayoutSubviews里
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
NSIndexPath *indexPath = // compute some index path
[self.collectionView scrollToItemAtIndexPath:indexPath
atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
animated:YES];
}
或者在调用 scrollToItemAtIndexPath 前加上 layoutIfNeed
[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];
}];