Since UICollectionView doesn't support reordering in the same convenient way UITableView does, it takes a bit more work to set it up. For UITableView, we only had to set a property on the cells and implement a delegate method. This was very simple and worked well straight out of the box.
To reorder cells in UICollectionView, it's required to implement a couple of steps. Luckily, Apple's documentation provides great information on reordering; if you have a look at the documentation for UICollectionView, you'll see that there are four methods related to reordering. Each of these four methods has its own role in the act of reordering and you are expected to call each of them yourself at the appropriate time.
The endInteractiveMovement() and beginInteractiveMovementForItem(at:) methods are interesting because after calling these methods, a data source method on UICollectionView is called. When ending the interactive movement, the UICollectionView asks the data source to update the selected item by moving it to a new index path. When beginning an interactive movement, the UICollectionViewDataSource is asked to confirm that it supports reordering of data.
The collection view does not keep track of moving cells around on its own; this needs to be implemented by you. A pan gesture recognizer can be added to achieve this, but the existing long-press gesture recognizer can also keep track of the movements that the user makes.
In order to reuse the existing long-press gesture recognizer without causing conflicts with deletion, an edit button should be added to the collection view. If the edit button is active, reordering is enabled and if it's inactive, the deletion of cells is enabled when long-pressing.
The steps to implement cell reordering are as follows:
- Refactor the long-press handler so it calls methods based on the editing state to prevent it from becoming a long, confusing method.
- Implement the sequence of methods for cell reordering based on the long-press gesture state.
- Implement the required data source methods to allow interactive movement and update the underlying data.
- Adding the edit button to the navigation item.