Implementing cell selection for a collection view is almost identical to implementing it on a table view. With the knowledge you have gained in the previous chapter, you should be able to implement basic cell selection on your own. To keep this section interesting, you won't implement the same alert as you did in the previous chapter. Because users like to see some feedback when they tap something that they can interact with, it's a great idea to add a little animation to your collection view cells to make them bounce a little bit when they are tapped.
Add the following UICollectionViewDelegate extension to ViewController.swift. Don't forget to set your view controller as the delegate for your collection view in viewDidLoad():
extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? ContactCollectionViewCell else { return } UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseOut], animations: { cell.contactImage.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) }, completion: { _ in UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseIn], animations: { cell.contactImage.transform = .identity }, completion: nil) }) } }
This snippet implements a simple animation using UIView.animate. In Chapter 4, Immersing your users with animation, you will learn more about animations, and you'll see other, more powerful ways to enable rich interactions to your app.
Note that the collection view is asked for the tapped cell using an index path. Since this method returns a UICollectionViewCell? object, you need to make sure that a cell was found and you must also cast it to a ContactCollectionViewCell object to access the contact image. If no cell exists at the requested index path or if the obtained cell is not a ContactCollectionViewCell object, the method is aborted.
If the cell is retrieved successfully, the animation is performed. The animate method takes several parameters that you will learn more about later. Chapter 4, Immersing your users with animation covers animation in depth, and you will be up to speed with what exactly is going on in this bounce animation in no time. For now, you might want to go ahead and run the app to see your bounce animation in action. If your animation doesn't work, double-check that you have set ViewController as the collection view's delegate.