Execute action when back bar button of UINavigationController is pressed

StevenR picture StevenR · Dec 30, 2014 · Viewed 198.5k times · Source

I need to execute an action (emptying an array), when the back button of a UINavigationController is pressed, while the button still causes the previous ViewController on the stack to appear. How could I accomplish this using swift? enter image description here

Answer

manecosta picture manecosta · Dec 31, 2014

Replacing the button to a custom one as suggested on another answer is possibly not a great idea as you will lose the default behavior and style.

One other option you have is to implement the viewWillDisappear method on the View Controller and check for a property named isMovingFromParentViewController. If that property is true, it means the View Controller is disappearing because it's being removed (popped).

Should look something like:

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

    if self.isMovingFromParentViewController {
        // Your code...
    }
}

In swift 4.2

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

    if self.isMovingFromParent {
        // Your code...
    }
}