Appearing and Disappearing Views

Whenever a UINavigationController is about to swap views, it calls two methods: viewWillDisappear(_:) and viewWillAppear(_:). The UIViewController that is about to be popped off the stack has viewWillDisappear(_:) called on it. The UIViewController that will then be on top of the stack has viewWillAppear(_:) called on it.

To hold on to changes in the data, when a DetailViewController is popped off the stack you will set the properties of its item to the contents of the text fields. When implementing these methods for views appearing and disappearing, it is important to call the superclass’s implementation – it might have some work to do and needs to be given the chance to do it.

In DetailViewController.swift, implement viewWillDisappear(_:).

Listing 12.2  Updating the Item values (DetailViewController.swift)

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    // "Save" changes to item
    item.name = nameField.text ?? ""
    item.serialNumber = serialNumberField.text

    if let valueText = valueField.text,
        let value = numberFormatter.number(from: valueText) {
        item.valueInDollars = value.intValue
    } else {
        item.valueInDollars = 0
    }
}

Now the values of the Item will be updated when the user taps the Back button on the UINavigationBar. When ItemsViewController appears back on the screen, the method viewWillAppear(_:) is called. Take this opportunity to reload the UITableView so the user can immediately see the changes.

In ItemsViewController.swift, override viewWillAppear(_:) to reload the table view.

Listing 12.3  Reloading the table view when coming onscreen (ItemsViewController.swift)

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    tableView.reloadData()
}

Build and run your application once again. Now you can add items, move back and forth between the view controllers that you created, and change the data with ease.

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

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