I'm using a UICollectionViewDiffableDataSource and a NSFetchedResultsController
to populate my UICollectionView
inside my UIViewController
.
To add the ability of reordering cells I added a UILongPressGestureRecognizer
and subclassed UICollectionViewDiffableDataSource
in order to use it's canMoveItemAt:
and moveItemAt:
methods.
When reordering a cell the following things happen:
moveItemAt:
is called and I update the objects position property and save the MOCcontrollerDidChangeContent:
of theNSFetchedResultsControllerDelegate
is called and I create a new snapshot from the current fetchedObjects and apply it.
When I apply dataSource?.apply(snapshot, animatingDifferences: true)
the cells switch positions back immediately. If I set animatingDifferences: false
it works, but all cells are reloaded visibly.
Is there any best practice here, how to implement cell reordering on a UICollectionViewDiffableDataSource
and a NSFetchedResultsController
?
Here are my mentioned methods:
// 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)
}
}