gpt4 book ai didi

ios - ScrollToItemAtIndexPath 有时不起作用

转载 作者:行者123 更新时间:2023-11-28 06:47:02 28 4
gpt4 key购买 nike

在我的集合中,一个 UICollectionView 实例,有 25 个单元格。第一个单元格位于 indexPath (0,0),最后一个单元格位于 indexPath (0,24)。

无论我从第一个单元格滚动到最后一个单元格还是从最后一个单元格滚动到第一个单元格,目标单元格始终为 nil,这似乎是 scrollToItemAtIndexPath 函数没有将单元格滚动到可见。

当我从第二个单元格滚动到第一个单元格时,一切顺利。

如何在第一个和最后一个之间正确滚动?我试过 layoutIfNeeded,但没什么不同。

这是我的部分代码:

    collection.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredVertically, animated: false)
print("indexPath")
print(indexPath)
guard let senderCell = collection.cellForItemAtIndexPath(indexPath) as? ImageCollectionViewCell else{
print(collection.cellForItemAtIndexPath(indexPath))
return
}

在控制台中:

    indexPath
<NSIndexPath: 0x79e53110> {length = 2, path = 0 - 24}
nil
indexPath
<NSIndexPath: 0x7b8c2690> {length = 2, path = 0 - 0}
nil
indexPath
<NSIndexPath: 0x79fc48e0> {length = 2, path = 0 - 1}
indexPath
<NSIndexPath: 0x79eb3950> {length = 2, path = 0 - 0}

最佳答案

我发现调用 scrollToItemAtIndexPathcollectionView 更新新的可见单元格之间有一个时间间隔。

所以我改变了我的代码如下:

collection.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredVertically, animated: false)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {[unowned self] in
guard let senderCell = collection.cellForItemAtIndexPath(indexPath) as? ImageCollectionViewCell else{
print("senderCell no found")
return
}
//Do something with the senderCell
}

通过添加一个delayTime来等待更新可见单元格,我们可以得到我们滚动到的单元格。

关于ios - ScrollToItemAtIndexPath 有时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36029558/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com