I would like to perform some actions when a user presses the "Back" button on my Navigation Controller. Is there a Swift function that is called when this happens?
5 Answers
Try this (copied and pasted from manecosta)
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...
}
}
Here is the link to the other question
Try to call this
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.isMovingFromParent {
print("isMovingFromParent()") // dismiss for push viewController
}
if self.isBeingDismissed {
print("isBeingDismissed()") // dismiss for modal that doesn't has navigationController
}
if self.navigationController?.isBeingDismissed ?? false {
print("navigationController?.isBeingDismissed()") // dismiss for modal that has navigationController
}
}

- 417
- 5
- 11
-
1This looks more precise than the accepted question. – JBarros35 Jan 20 '20 at 11:10
override func viewWillDisappear(animated: Bool) {
// Do Your Lines of Code ...
}
Everytime when back button or Done is pressed or a view is popped out this function is called.. you need to override this..

- 863
- 8
- 14
-
12Keep in mind using this will also be called if the viewController presents or pushes another viewController. – Slayter Apr 08 '16 at 18:24
Try this:
override func willMoveToParentViewController(parent: UIViewController?) {
if parent == nil {
// Back button Event handler
}
}

- 11,328
- 15
- 80
- 116
-
I tested this and the weird thing is that this function is called before I get to the view controller, as well as when I click the back button. Unfortunately that will not work for me. Adbul's function is called when I need it to be. – GED125 Apr 08 '16 at 17:59
-
1Abdul's function sometime will got some error if the current ViewController continue to push to another ViewController. – Twitter khuong291 Apr 08 '16 at 18:03
-
-
The function name is changed in Swift 4 (or 3) to `willMove(toParentViewController:)`. If this method doesn't get called, is your viewController inside `UINavigationController`? Does it has own back-button instead of the one supplied by `UINavigationController`? – John Pang Sep 13 '18 at 17:03
Swift 5
"viewWillDisappear" call Every time for forward or backward. But if you add this check it's call only when back from controller.
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingFromParent {
print("Only back action")
}
}

- 109
- 6