Passing the model to the details page

The transition from the overview page to the details page is implemented with a segue. The segue is triggered when the user taps a contact, putting the detail page on the screen. Because this transition uses a segue, there is a special method that can be implemented to pass data from the first view controller to the second view controller. This special method is called prepare(for:sender:).

This method is called on the source view controller right before a segue is performed and it provides access to the destination view controller. The segue's destination is used to configure data on the view controller that is about to be presented. Let's implement this right now so you can pass the tapped contact to the detail page. Add the following extension to ViewController.swift:

extension ViewController {
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let contactDetailVC = segue.destination as? ContactDetailViewController,
      segue.identifier == "detailViewSegue",
      let selectedIndex = collectionView.indexPathsForSelectedItems?.first {
        contactDetailVC.contact = contacts[selectedIndex.row]
    }
  }
}

This implementation first verifies that the destination of the segue has the correct type. Then, it also makes sure that the segue's identifier matches the identifier that was added for this segue in Interface Builder. Finally, the first (and only) selected index path is read from the collection view. This information is then used to assign the correct contact from the contacts array to a contact property on the destination view controller. This property does not exist yet, but you will add it to ContactDetailViewController in a moment.

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

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