我采用了新的 UICollectionViewDiffableDataSource。每次删除项目时,我都会应用数据源快照:
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(items)
apply(snapshot, animatingDifferences: true)
删除是通过内置的集合视图配置选项提供的:
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard let item = dataSource.itemIdentifier(for: indexPath) else {
return nil
}
let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash.fill"), attributes: .destructive) { _ in
self.deleteItem(item)
}
return UIMenu(title: "", image: nil, identifier: nil, children: [delete])
}
return configuration
}
如果我从上下文菜单之外删除该项目,则动画效果很好。如果我从上下文菜单中删除,则一个单元格消失,然后导致下一个单元格闪烁。我怀疑关闭上下文菜单和运行删除动画之间存在某种冲突。我正在寻找解决此问题的方法。