8

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()在未显示上下文菜单时调用,则删除动画按预期工作。

4

1 回答 1

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])
        })
    }
}

秒是对我有用的0.4最短延迟。

于 2019-09-18T16:17:41.470 回答