问题描述
在加载收集视图之前,用户设置收集视图数组中的图像数.屏幕上没有所有的单元格.我有30个单元格,屏幕上只有6个.
Before loading the collection view user sets the number of image in the array of collection view. All of the cells don't fit on the screen. I have 30 cells and only 6 on the screen.
问题:如何在加载UICollectionView时自动滚动到具有所需图像的单元格?
The question: How to scroll to the cell with desired image automatically at the load of UICollectionView?
推荐答案
我发现在viewWillAppear
中滚动可能无法可靠地工作,因为集合视图尚未完成其布局.您可能滚动到错误的项目.
I've found that scrolling in viewWillAppear
may not work reliably because the collection view hasn't finished it's layout yet; you may scroll to the wrong item.
我还发现在viewDidAppear
中滚动会导致未滚动视图的瞬时闪烁可见.
I've also found that scrolling in viewDidAppear
will cause a momentary flash of the unscrolled view to be visible.
并且,如果您每次在viewDidLayoutSubviews
中滚动,则用户将无法手动滚动,因为某些集合布局会在您每次滚动时导致子视图布局.
And, if you scroll every time through viewDidLayoutSubviews
, the user won't be able to manually scroll because some collection layouts cause subview layout every time you scroll.
这是我发现可靠工作的地方:
Here's what I found works reliably:
目标C:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// If we haven't done the initial scroll, do it once.
if (!self.initialScrollDone) {
self.initialScrollDone = YES;
[self.collectionView scrollToItemAtIndexPath:self.myInitialIndexPath
atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
}
}
迅速:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if (!self.initialScrollDone) {
self.initialScrollDone = true
self.testNameCollectionView.scrollToItem(at:selectedIndexPath, at: .centeredHorizontally, animated: true)
}
}
这篇关于UICollectionView自动滚动到IndexPath的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!