gpt4 book ai didi

ios - 删除一个后,如何获取新中心 UICollectionViewCell 的 indexPath?

转载 作者:行者123 更新时间:2023-11-28 13:59:41 25 4
gpt4 key购买 nike

我有一个名为 postsCollectionView 的水平 collectionView,其中每个都与屏幕一样宽。目前我正在计算 currentPost 的 indexPath:

let currentPostIndex = Int(self.postsCollectionView.contentOffset.x / self.postsCollectionView.frame.size.width)
let currentPostIndexPath = IndexPath(row: currentPostIndex, section: 0)

当帖子被删除并且我重置了“currentPost”时,我的 View Controller 中有这个 hacky 方法:

 func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if (postsFetchedResultsController.fetchedObjects?.count)! > 0 {
print(postsCollectionView.indexPathsForVisibleItems,postsCollectionView.contentOffset.x) //prints [],375.0
//HACK
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { // change 2 to desired number of seconds
let currentPostIndex = Int(self.postsCollectionView.contentOffset.x / self.postsCollectionView.frame.size.width)
let currentPostIndexPath = IndexPath(row: currentPostIndex, section: 0)
self.currentPost = self.postsFetchedResultsController.object(at: currentPostIndexPath)
}
} else {
print("no items left")
}
}

基本上有一个 NSFetchedResultsController 在数据源改变时调用 collectionView 的 deleteItem 方法。我正在使用回调 didEndDisplaying 单元格来尝试 - 当单元格被完全删除时,将 self.currentPost 设置为现在显示的已经取代它的帖子。

问题是我认为这个回调是在单元格被删除时调用的,但是动画还没有完成所以它仍然偏移 375(屏幕的宽度)所以它计算当前索引路径为 1 即使它应该是 0,因为现在 collectionView 中只有 1 个帖子。

有没有办法等到动画也完成?还是有更好的方法来计算删除一个 Collection View 单元格后位于中心的新 indexPath?

最佳答案

1) 为什么不将 currentPost 设置为 nil 并在实际需要时重新计算它,而不是在删除单元格后立即重新计算

2) 您可以使用 UICollectionView.indexPathForItem(at point: CGPoint) 来获取您的 IndexPath。它可能更安全一些。我想你传递的观点是

CGPoint(x:self.postsCollectionView.contentOffset.x, y:0) 

y 位置取决于您如何将单元格放置在 Collection View 中。

如果您立即需要结果。您知道删除前的当前索引。如果要删除的单元格的索引小于或等于该索引,则增加当前索引,如果删除的单元格的索引更大,则不要更改它。

关于ios - 删除一个后,如何获取新中心 UICollectionViewCell 的 indexPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53660336/

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