【发布时间】:2019-05-08 16:15:21
【问题描述】:
我有一个名为 postsCollectionView 的水平 collectionView,其中每个都与屏幕一样宽。目前我正在计算 currentPost 的 indexPath:
let currentPostIndex = Int(self.postsCollectionView.contentOffset.x / self.postsCollectionView.frame.size.width)
let currentPostIndexPath = IndexPath(row: currentPostIndex, section: 0)
当帖子被删除并且我重置了“currentPost”时,我的视图控制器中有这个 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 个帖子。
有没有办法等到动画也完成?或者有没有更好的方法来计算中心的集合视图单元格的新 indexPath 被删除后?
【问题讨论】:
标签: ios swift uicollectionview