Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a function when the navigation back button is pressed?

I need to call a function when I press the back button. Preferably, without having to create another button

like image 715
Leo Valentim Avatar asked Jan 31 '17 18:01

Leo Valentim


People also ask

How can I tell if my Android back button is pressed?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.

What is a navigation controller?

NavController manages app navigation within a NavHost . Apps will generally obtain a controller directly from a host, or by using one of the utility methods on the Navigation class rather than create a controller directly. Navigation flows and destinations are determined by the navigation graph owned by the controller.

Do all Android devices have a back button?

All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI. Depending on the user's Android device, this button might be a physical button or a software button.


2 Answers

Place the following in your view controller.

override func willMove(toParent parent: UIViewController?) {
    super.willMove(toParent: parent)

    if parent == nil {
        // The view is being removed from the stack, so call your function here
    }
}

When parent is nil, it means the view is being removed from the stack (ie the back button was pressed).

One consideration when compared with matt's answer is that willMove is called before viewWillDisappear. Your mileage will vary based on what your function does, but this can result in issues based on your specific needs. With that said, either answer is perfectly capable of providing what you requested.

like image 145
CodeBender Avatar answered Sep 22 '22 05:09

CodeBender


Implement viewWillDisappear and, in it, test isMovingFromParentViewController. If the latter is true, you're being popped.

like image 34
matt Avatar answered Sep 22 '22 05:09

matt