Implementing the data source methods

To support cell reordering, you must implement two UICollectionViewDataSource methods. The first method is collectionView(_:moveItemAt:). This method is called to determine whether the currently selected item can be moved around. The second method you must implement is collectionView(_:moveItemAt:to:). This method is called to tell the data source that it must commit the changes made by the user to the underlying data store. Let's jump straight into the implementation code. The following methods should be added to your UICollectionViewDataSource extension in ViewController.swift:

func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
  return true
}

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
  let movedContact = contacts.remove(at: sourceIndexPath.row)
  contacts.insert(movedContact, at: destinationIndexPath.row)
}

The first method always returns true because every item in the collection view can be reordered. The second method moves the reordered contact from its old position in the dataset to the new position. This is very similar to what you have done before to implement table view reordering. The last step to enable cell reordering is implementing the edit button in the navigation bar. When the user taps this button, the collection view enters edit mode, and the contacts can be dragged around after long-pressing them.

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

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