显示 UIContextMenu 时从 UICollectionView 删除项目时出现奇怪的动画

Hej*_*azi 8 ios uicollectionview swift uicontextmenuinteraction

我正在使用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])
    })
}
Run Code Online (Sandbox Code Playgroud)

一切正常,但是当我点击“删除”项目时,会发生一个奇怪的动画,其中已删除的项目留在原地而其他项目正在移动,然后它立即消失。有时我什至在新项目出现之前的几分之一秒内看到一个空白区域或一个随机项目。

如果我collectionView.deleteItems()在上下文菜单未显示时调用,则删除动画按预期工作。

Hej*_*azi 10

看起来奇怪的动画是两个几乎同时运行的动画之间冲突的结果:

  1. 删除动画:当点击“删除”项目时,collectionView.deleteItems()调用并通过动画删除指定的集合项目。
  2. 菜单关闭动画:点击菜单项后,上下文菜单也会关闭,并显示另一个动画,显示已删除的项目几分之一秒。

这看起来像是一个应该由 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])
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

0.4秒是为我工作的最短的延迟。

  • 0.7 延迟对我来说效果最好...我们必须做出这样的解决方法,这很糟糕,但是好吧,我想继续下一个 (2认同)