UICollectionView 自动滚动到 IndexPath 处的单元格 [英] UICollectionView auto scroll to cell at IndexPath
问题描述
在加载集合视图之前,用户设置集合视图数组中的图像数量.所有单元格都不适合屏幕.我有 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 处的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!