小编mrt*_*lst的帖子

使用 UICollectionViewDiffableDataSource 和 NSFetchedResultsController 重新排序单元格

我正在使用UICollectionViewDiffableDataSource和 aNSFetchedResultsController来填充UICollectionView我的UIViewController.

为了添加重新排序单元格的能力,我添加了一个UILongPressGestureRecognizer和子类UICollectionViewDiffableDataSource以便使用它的canMoveItemAt:moveItemAt:方法。

对单元格重新排序时,会发生以下情况:

  1. moveItemAt: 被调用,我更新对象位置属性并保存 MOC
  2. controllerDidChangeContent:NSFetchedResultsControllerDelegate被调用,我从当前的 fetchedObjects 创建一个新快照并应用它。

当我应用dataSource?.apply(snapshot, animatingDifferences: true)单元格时,立即切换位置。如果我设置animatingDifferences: false它有效,但所有单元格都可见地重新加载。

这里有什么最佳实践,如何在 aUICollectionViewDiffableDataSource和 a上实现单元格重新排序NSFetchedResultsController

以下是我提到的方法:

// ViewController 
func createSnapshot(animated: Bool = true) {
    var snapshot = NSDiffableDataSourceSnapshot<Int, Favorite>()
    snapshot.appendSections([0])
    snapshot.appendItems(provider.fetchedResultsController.fetchedObjects ?? [])
    dataSource?.apply(snapshot, animatingDifferences: animated)
}

// NSFetchedResultsControllerDelegate
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    createSnapshot(animated: false)
}

// Subclassed …
Run Code Online (Sandbox Code Playgroud)

nsfetchedresultscontroller ios uicollectionview swift ios13

8
推荐指数
1
解决办法
712
查看次数