I need to do certain things when my view controller is both pushed or popped from the navigation stack, but don't want to use viewillappear / viewdidappear or viewwilldisappear / viewdiddisappear since those cover cases besides when the view controller is pushed / popped. Is the correct way to go about this to use the navigationcontroller delegate and the navigationController:didShowViewController:animated: and navigationController:willShowViewController:animated: ? If not, how is the best way to go about this?
To find out when it's pushed, you can use the
UINavigationControllerDelegate
and implement
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated
This method will fire whenever the viewcontroller is pushed into the navigation stack, and whenever the viewcontroller on top of it is popped off, thus revealing it again. So you have to use a flag to figure out if it's been initialized yet, if it hasn't means it just was pushed.
To find out when it's been popped, use this answer:
viewWillDisappear: Determine whether view controller is being popped or is showing a sub-view controller
You can try UINavigationController delegate methods it calls when object push or pop from navigation controller stack.
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
Here's an example to detect when a view controller is being pushed onto the navigation stack by overriding -viewWillAppear:
and popped by overriding -viewWillDisappear:
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (self.isMovingToParentViewController) {
NSLog(@"view controller being pushed");
}
}
-(void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (self.isMovingFromParentViewController) {
NSLog(@"view controller 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