显示UIContextMenu时从UICollectionView删除项目时出现怪异的动画 [英] Weird animation when deleting item from UICollectionView while UIContextMenu is shown
问题描述
我正在使用UIContextMenuInteraction
来显示UICollectionView
的上下文菜单,如下所示:
I'm using UIContextMenuInteraction
to show a context menu for UICollectionView
as follows:
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])
})
}
一切正常,但是当我点击删除"项目时,出现奇怪的动画,其中删除的项目保留在原处,而其他项目在移动,然后立即消失.有时我什至在出现新项目之前几秒钟就看到一个空白区域或一个随机项目.
Everything works well, but when I tap the "Delete" item, a weird animation happens where the deleted item stays in its place while other items are moving, and then it disappears instantly. And sometimes I even see an empty space or a random item for fraction of a second before the new item appears.
如果在未显示上下文菜单的情况下调用collectionView.deleteItems()
,则删除动画将按预期工作.
If I call collectionView.deleteItems()
while the context menu isn't shown the deletion animation works as expected.
推荐答案
看起来奇怪的动画是几乎同时运行的两个动画之间发生冲突的结果:
It looks like the weird animation is a result of a conflict between two animations that run at almost the same time:
- 删除动画:轻按删除"项目时,将调用
collectionView.deleteItems()
并使用动画删除指定的收集项目. - 菜单关闭动画:点击菜单项后,上下文菜单也将与另一个动画一起关闭,该动画会在短短的一秒钟内显示已删除的项目.
- Deletion animation: When "Delete" item is tapped,
collectionView.deleteItems()
is called and the specified collection item is deleted with animation. - Menu dismiss animation: After the menu item is tapped, the context menu is also dismissed with another animation that shows the deleted item for a fraction of a second.
这看起来像是应该由Apple修复的错误.但是,作为一种解决方法,我不得不将删除操作延迟到解雇动画完成之前:
This looks like a bug that should be fixed by Apple. But as a workaround, I had to delay the deletion until the dismiss animation completed:
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
秒是对我有用的最短延迟.
The 0.4
seconds is the shortest delay that worked for me.
这篇关于显示UIContextMenu时从UICollectionView删除项目时出现怪异的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!