Step 2 in the process of implementing cell reordering is to keep the collection view informed of the state it needs to be in. This is done by tracking the long-press gesture recognizer state and calling appropriate methods on the collection view. Any time the long-press gesture recognizer updates, either when the gesture was first recognized, ended, moved around, or got canceled, the handler is called. The handler will detect that the ViewController is in edit mode, and the reorderContact(withCell:atIndexPath) method is called. Its implementation looks like the following:
func reorderContact(withCell cell: UICollectionViewCell, atIndexPath indexPath: IndexPath, gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case .began:
collectionView.beginInteractiveMovementForItem(at: indexPath)
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut], animations: {
cell.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
}, completion: nil)
break
case .changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: collectionView))
break
case .ended:
collectionView.endInteractiveMovement()
break
default:
collectionView.cancelInteractiveMovement()
break
}
}
The gesture's state property is used in a switch statement so we can easily cover all possible values. If the gesture just began, the collection view will enter the reordering mode. We also perform an animation on the cell so the users can see that their gesture was properly registered.
If the gesture has changed, because the user dragged the cell around, we tell this to the collection view. The current position of the gesture is passed along so that the cell can be moved to the correct direction. If needed, the entire layout will animate to show the cell in its new location.
If the gesture ended, the collection view is notified of this. The default case in the switch statement is to cancel the interactive movement. Any state that isn't in the states above is invalid for this use case, and the collection view should reset itself as if the editing never even began. The next step is to implement the required data source methods so the collection view can call them to determine whether cell reordering is allowed and to commit the changes made to its data source.