Reordering cells in a collection view

Since collection views don't have the same awesome reordering API that table views have, you'll need to do a little bit of extra work again to get this to work. Doing extra work doesn't mean that implementing reordering is extremely complex, quite the opposite. There are some nice delegate methods available that aid greatly in implementing reordering for your collection view.

It will take a couple of steps to implement reordering for your collection view. Apple's documentation for UICollectionView lists several methods that relate to collection view reordering. Every method has its place in the reorder interaction, and you are expected to call each one at the right time on the collection view. Two methods from this list are of special interest:

  • endInteractiveMovement()
  • beginInteractiveMovementForItem(at:)

These two methods are interesting because when you call these on your collection view, the collection view will then call methods on its data source. When you end the interactive movement, the data source is asked to update its underlying dataset by moving an item from its old index path to a new index path. When you call beginInteractiveMovementForItem(at:), the data source is asked whether the currently selected item is allowed to be reordered.

Collection views do not keep track of moving cells around on its own; you must implement this yourself. You can do this by adding a pan gesture recognizer but, coincidentally, the long-press gesture recognizer can also track movements the user makes with their finger.

To reuse the existing long-press gesture recognizer, you will need to refactor it a little bit. To differentiate between wanting to delete or move a cell, an edit button should be added to the collection view. The user can then tap this button to toggle between edit mode and normal mode. When the collection view is in edit mode, it allows cell reordering and otherwise it allows users to delete items.

To implement reordering, you will perform the following steps:

  1. Refactor the long-press handler to differentiate between reordering and deleting cells.
  2. Implement the sequence of method calls for cell reordering based on the gesture recognizer's state.
  3. Implement the data source methods that allow cell reordering.
  4. Add the edit button to the navigation bar.