Search code examples
iosuinavigationcontroller

Detect if default back button in navigation bar is pressed


I know that there are answers to this like make custom button and then make action but I don't want to change the default back button with arrow and I also tried like this:

override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}

Here the problem is that this function gets called even if I press on save button that I also have in that view controller. I need to detect only when the back button is pressed


Solution

  • In your viewWillDisappear method, add the isMovingFromParentViewController property:

    if self.isMovingFromParentViewController {
        //do stuff, the back button was pressed
    }
    

    EDIT: As had pointed out, if you are merely dismissing the view controller when the save button is pressed, you need a Bool value to check if the save button was pressed or the default back button.

    At the top of your class, define a Boolean value:

    var saveButtonPressed = false
    

    I'm assuming that you have an @IBAction method linked to your save button. If you don't, then I suggest you add that connection.

    In that method, set saveButtonPressed equal to true.

    Then, in your viewWillDisappear method, add this to the if condition:

    if (self.isMovingFromParentViewController && !saveButtonPressed) {
        //do stuff, the back button was pressed
    }