如何在 Swift 中的特定索引处显示 collectionView
How to show a collectionView at a Specific Index in Swift
我正在使用位于 github 上的名为 VegaScrollFlowLayout 的库。我试图在我的 collectionView 中给出一个确切的索引,并从该索引开始显示数据,但我一直重置回索引 0 而不是索引 10。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.scrollToItem(
at: NSIndexPath(item: 10, section: 0) as IndexPath,
at: [],
animated: false)
}
好吧,经过一番挖掘,我不得不在代码中添加延迟。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)
{
self.collectionView.scrollToItem(
at: NSIndexPath(item: 15, section: 0) as IndexPath,
at: [],
animated: false)
}
}
这解决了问题。
您可能应该在 viewDidAppear()
中拨打 scrollToItem(at:at:animated:)
,而不是 viewWillAppear()
。在 viewWillAppear()
中,集合视图尚未显示任何单元格。我认为您不需要那样延迟。
使用延迟是一种脆弱的做事方式。最好将代码移动到正确的生命周期方法。
我正在使用位于 github 上的名为 VegaScrollFlowLayout 的库。我试图在我的 collectionView 中给出一个确切的索引,并从该索引开始显示数据,但我一直重置回索引 0 而不是索引 10。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.scrollToItem(
at: NSIndexPath(item: 10, section: 0) as IndexPath,
at: [],
animated: false)
}
好吧,经过一番挖掘,我不得不在代码中添加延迟。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)
{
self.collectionView.scrollToItem(
at: NSIndexPath(item: 15, section: 0) as IndexPath,
at: [],
animated: false)
}
}
这解决了问题。
您可能应该在 viewDidAppear()
中拨打 scrollToItem(at:at:animated:)
,而不是 viewWillAppear()
。在 viewWillAppear()
中,集合视图尚未显示任何单元格。我认为您不需要那样延迟。
使用延迟是一种脆弱的做事方式。最好将代码移动到正确的生命周期方法。