Implementing the reordering method calls

The second step to implement cell reordering is to call the correct UICollectionView methods at the right times. To do so, the long-press gesture's state is tracked and used to inform the collection view about the current state of the reorder life cycle it should be in. Add the following implementation for beginReorderingForCell(_:atIndexPath:gestureRecognizer:):

func beginReorderingForCell(_ cell: UICollectionViewCell, atIndexPath indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  switch gestureRecognizer.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)
  case .changed:
    let position = gestureRecognizer.location(in: collectionView)
    collectionView.updateInteractiveMovementTargetPosition(position)
  case .ended:
    collectionView.endInteractiveMovement()
  default:
    collectionView.endInteractiveMovement()
  }
}

You can use a gesture recognizer's state property to find out more about the state it is in and take action based on this state. In this case, when the gesture begins, the collection view should enable its interactive movement mode for the pressed index path. To inform the user that the cell is being dragged, it is also made slightly larger using an animation.

When the recognizer updates, and it's in the changed state, the collection view should update accordingly. The collection view is informed about the position of the user's finger so it can update the visible cells to make room for the cell that is now hovering at a new location.

If the gesture is ended, or in another state, the interactive movement is ended. This means that the collection view will ask the data source to update its underlying data and the interface is animated to its new state. Since the collection view communicates with its data source for cell reordering, the next logical step is to update the data source, so it allows items to be reordered, and to make it persist the changes made by the user into the underlying data storage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset