我正在使用UIContextMenuInteraction
来显示UICollectionView
的上下文菜单,如下所示:
func collectiovnView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { _ in
let deleteAction = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { _ in
self.deleteItem(at: indexPath)
}
return UIMenu(title: "Actions", children: [deleteAction])
})
}
func deleteItem(at indexPath: IndexPath) {
self.collectionView.performBatchUpdates({
self.items.remove(at: indexPath.item)
self.collectionView.deleteItems(at: [indexPath])
})
}
一切正常,但是当我点击"删除"项目时,会发生一个奇怪的动画,删除的项目停留在其位置,而其他项目正在移动,然后它立即消失。有时我什至会在新项目出现之前的几分之一秒内看到一个空白区域或随机项目。
如果我在上下文菜单未显示的情况下调用collectionView.deleteItems()
则删除动画将按预期工作。
看起来奇怪的动画是几乎同时运行的两个动画之间冲突的结果:
删除- 动画:点击"删除"项时,调用
collectionView.deleteItems()
,并通过动画删除指定的集合项。
菜单关闭动画 - :点击菜单项后,上下文菜单也会关闭,并显示另一个动画,该动画显示已删除的项目几分之一秒。
这看起来像是一个应该由Apple修复的错误。但作为一种解决方法,我不得不延迟删除,直到关闭动画完成:
func deleteItem(at indexPath: IndexPath) {
let delay = 0.4 // Seconds
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.collectionView.performBatchUpdates({
self.items.remove(at: indexPath.item)
self.collectionView.deleteItems(at: [indexPath])
})
}
}
0.4
秒是对我来说最短的延迟。