我正在使用UICollectionViewDiffableDataSource和NSFetchedResultsController
将我的UICollectionView
填充到我的UIViewController
中。
[为了增加对单元格重新排序的能力,我添加了一个UILongPressGestureRecognizer
并将其分类为UICollectionViewDiffableDataSource
,以便使用它的canMoveItemAt:
和moveItemAt:
方法。
[对单元格重新排序时,会发生以下情况:
moveItemAt:
被调用,并且我更新对象的位置属性并保存MOCcontrollerDidChangeContent:
的[NSFetchedResultsControllerDelegate
被调用,我从当前的fetchedObjects创建一个新快照并应用它。[当我应用dataSource?.apply(snapshot, animatingDifferences: true)
时,单元格立即切换位置。如果设置为animatingDifferences: false
,它可以工作,但是所有单元格都将重新加载。这里是否有最佳实践,如何在UICollectionViewDiffableDataSource
和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 UICollectionViewDiffableDataSource
override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
provider.moveFavorite(from: sourceIndexPath.row, to: destinationIndexPath.row)
}
// Actual cell moving in a provider class
public func moveFavorite(from source: Int, to destination: Int) {
guard let favorites = fetchedResultsController.fetchedObjects else { return }
if source < destination {
let partialObjects = favorites.filter({ $0.position <= destination && $0.position >= source })
for object in partialObjects {
object.position -= 1
}
let movedFavorite = partialObjects.first
movedFavorite?.position = Int64(destination)
}
else {
let partialObjects = favorites.filter({ $0.position >= destination && $0.position <= source })
for object in partialObjects {
object.position += 1
}
let movedFavorite = partialObjects.last
movedFavorite?.position = Int64(destination)
}
do {
try coreDataHandler.mainContext.save()
} catch let error as NSError {
print(error.localizedDescription)
}
}
我正在使用UICollectionViewDiffableDataSource和NSFetchedResultsController在UIViewController中填充我的UICollectionView。为了增加对单元格重新排序的能力,我添加了一个...