Ser Pounce Ser Pounce - 2 months ago 26
iOS Question

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?

Answer

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 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