Segue using Diffable Data Sources

Code below in the `didSelectRowAt` function shows how we can retrieve an item and segue to a detail view controller.

import UIKit

struct Country: Hashable {
  let name: String
}

class DetailViewController: UIViewController {
  private var country: Country
  
  init(country: Country) {
    self.country = country
    super.init(nibName: nil, bundle: nil)
  }
  
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

class SampleViewController: UIViewController {
  private var dataSource: UICollectionViewDiffableDataSource<Int, Country>!
  private var tableView: UITableView!
  
  override func viewDidLoad() {
    super.viewDidLoad()
  }
}

extension SampleViewController: UITableViewDelegate {
  // segue to detail view controller
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let country = dataSource.itemIdentifier(for: indexPath) else {
      return
    }
    let detailVC = DetailViewController(country: country)
    navigationController?.pushViewController(detailVC, animated: true)
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s