[英]UICollectionView scrollToItemAtIndexPath
I'm trying to scroll to a specific item in a collection view and it seems to happening properly about 90 % of the time. 我正在尝试滚动到集合视图中的特定项目,它似乎在90%的时间内正常发生。 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.
当我在scrollToItemAtIndexPath上放置一个断点时,似乎当它工作时,项目大小已经生效,但是它不起作用的时间,单元格仍然具有旧的大小。 How can I make sure the itemSize has changed before scrolling?
如何在滚动之前确保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];
}];
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];
}
Another option is to call layoutIfNeeded
on the UICollectionView
before you call scrollToItemAtIndexPath
. 另一种选择是在调用
scrollToItemAtIndexPath
之前在UICollectionView
上调用layoutIfNeeded
。 That way you won't perform the scroll operation every time the parent view's subviews are laid out. 这样,每次布置父视图的子视图时,您都不会执行滚动操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.