Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to be alerted when uiviewcontroller is pushed / popped from navigation stack

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?

like image 803
Ser Pounce Avatar asked Jan 11 '12 07:01

Ser Pounce


3 Answers

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

like image 199
Ser Pounce Avatar answered Oct 19 '22 08:10

Ser Pounce


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;
like image 6
iOSPawan Avatar answered Oct 19 '22 08:10

iOSPawan


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");
    }
}
like image 3
MobileDev Avatar answered Oct 19 '22 09:10

MobileDev