NO
override func willMove(toParentViewController parent: UIViewController?) { }
This will get called even if you are segueing to the view controller in which you are overriding this method. In which check if the "parent
" is nil
of not is not a precise way to be sure of moving back to the correct UIViewController
. To determine exactly if the UINavigationController
is properly navigating back to the UIViewController
that presented this current one, you will need to conform to the UINavigationControllerDelegate
protocol.
YES
note: MyViewController
is just the name of whatever UIViewController
you want to detect going back from.
1) At the top of your file add UINavigationControllerDelegate
.
class MyViewController: UIViewController, UINavigationControllerDelegate {
2) Add a property to your class that will keep track of the UIViewController
that you are segueing from.
class MyViewController: UIViewController, UINavigationControllerDelegate {
var previousViewController:UIViewController
3) in MyViewController
's viewDidLoad
method assign self
as the delegate for your UINavigationController
.
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.delegate = self
}
3) Before you segue, assign the previous UIViewController
as this property.
// In previous UIViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourSegueID" {
if let nextViewController = segue.destination as? MyViewController {
nextViewController.previousViewController = self
}
}
}
4) And conform to one method in MyViewController
of the UINavigationControllerDelegate
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController == self.previousViewController {
// You are going back
}
}