Solution for Ch 14 Gold Challenge: Pushing More View Controllers


#1
//  Item.swift

class Item: NSObject {
//  let dateCreated: Date
  var dateCreated: Date
//  DatePickerViewController.swift

import UIKit

class DatePickerViewController: UIViewController {
  var datePicker: UIDatePicker!
  
  var item: Item!

  override func loadView() {
    let view = UIView()
    view.backgroundColor = UIColor.white
    self.view = view
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Date Created"

    datePicker = UIDatePicker()
    datePicker.datePickerMode = .date
    datePicker.date = item.dateCreated
    datePicker.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(datePicker)

    datePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    datePicker.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    item.dateCreated = datePicker.date
  }
}

Add a new button underneath the dateLabel in DetailViewController with the title “Change Date”.
Add an action for the new button in the DetailViewController.

//  DetailViewController.swift

class DetailViewController: UIViewController {
...
  @IBAction func ChangeDate(_ sender: UIButton) {
    let datePickerViewController = DatePickerViewController()
    datePickerViewController.item = item
    self.navigationController?.pushViewController(datePickerViewController, animated: true)
  }
}