I need to call a function when I press the back button. Preferably, without having to create another button
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.
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.
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.
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.
Implement viewWillDisappear
and, in it, test isMovingFromParentViewController
. If the latter is true, you're being popped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With