I need to know when my view controller is about to get popped from a nav stack so I can perform an action.
I can't use -viewWillDisappear, because that gets called when the view controller is moved off screen for ANY reason (like a new view controller being pushed on top).
I specifically need to know when the controller is about to be popped itself.
Any ideas would be awesome, thanks in advance.
They are separate classes: UIView is a class that represents the screen of the device of everything that is visible to the viewer, while UIViewController is a class that controls an instance of UIView, and handles all of the logic and code behind that view.
Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy. A view controller's main responsibilities include the following: Updating the contents of the views, usually in response to changes to the underlying data.
First UIViewController is alloc'ed by some other object, then init is immediately called (or some other init method, like initWithStyle). Only once the object is initialized would I expect it to call its own loadView function, after which the view, once loaded, calls the viewDidLoad delegate method.
A UIViewController is an object which manages the view hierarchy of the UIKit application. The UIViewController defines the shared behavior and properties for all types of ViewController that are used in the iOS application. The UIViewController class inherits the UIResponder class. ADVERTISEMENT. ADVERTISEMENT.
Override the viewWillDisappear
method in the presented VC, then check the isMovingFromParentViewController
flag within the override and do specific logic. In my case I'm hiding the navigation controllers toolbar. Still requires that your presented VC understand that it was pushed though so not perfect.
Fortunately, by the time the viewWillDisappear method is called, the viewController has already been removed from the stack, so we know the viewController is popping because it's no longer in the self.navigationController.viewControllers
Swift 4
override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let nav = self.navigationController { let isPopping = !nav.viewControllers.contains(self) if isPopping { // popping off nav } else { // on nav, not popping off (pushing past, being presented over, etc.) } } else { // not on nav at all } }
Original Code
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; if ((self.navigationController) && (![self.navigationController.viewControllers containsObject:self])) { NSLog(@"I've been 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