Adding the edit button

Adding an edit button to a navigation bar is fairly straightforward. Add the following code to the viewDidLoad() method of ViewController:

navigationItem.rightBarButtonItem = editButtonItem

If you build and run your app now, you can immediately begin dragging contacts around to reorder them. However, it's not really obvious that cells are in a different state after entering edit mode. The home screen on an iPhone does a great job at indicating when it's in edit mode. The icons begin to wiggle so the user knows they can now be moved around freely.

For now, an animation like that is a little bit too advanced so, for now, the cells will just be given a different background color to indicate that they are now in a different state. Add the following code to ViewController to update the cell's background color:

override func setEditing(_ editing: Bool, animated: Bool) {
  super.setEditing(editing, animated: animated)

  for cell in collectionView.visibleCells {
    UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut], animations: {
      if editing {
        cell.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
      } else {
        cell.backgroundColor = .clear
      }
    }, completion: nil)
  }
}

This updates all currently visible cells. However, because the collection view proactively keeps some off-screen cells in memory, you need to make sure to update those as well. You can implement collectionView(_:willDisplay:forItemAt:) to configure a cell right before it becomes visible to the user. This method is great for updating cells that are loaded but haven't become visible yet. Implement the following method on your UICollectionViewDelegate extension:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  if isEditing {
    cell.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
  } else {
    cell.backgroundColor = .clear
  }
}

That's it! Try running your app now to see all your hard work come together. Even though not every feature was as simple to implement on a collection view as it was on a table view, they are truly similar and the benefits of being able to create your own custom layout make the collection view one of the most important components to master in iOS.

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

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