I have numerous ViewControllers within a NavigationController setup and was wondering if it's possible to run code when the user clicks "back".
Basically my app runs a test and I would like "back" to also stop the test. I know I can add a separate stop button but this would be smoother.
Thanks
EDITED:
I have added:
-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([[StdTCPTestViewController class] isSubclassOfClass:[ViewController class]])
NSLog(@"We are going back to VC1");
}
to my code but this gets called as soon as the view loads, not when the back button is pressed. The StdTCPTestViewController is VC2 and ViewController is VC1 in the example below. NavController -- VC1 -- VC2 is the hierarchy and the segue is push from VC1 to VC2.
Any other tweaks?
Let's assume you have 2 VCs in the Navigation Controller stack:
Every time VC2 is "pushed" onto the navigation controller stack: viewDidLoad of VC2 is called. And everytime it is "popped", the view is unloaded. On the other hand, VC1 on the stack does not call its viewDidload (when VC2 is popped) since VC1 is still loaded in memory (remember you were pushing VC2 on top of VC1 so VC1 must have stayed in memory!)
So in a way, if you want some code executed when the back button is pressed, you should put that code in the viewDidAppear (or viewWillAppear) method of VC1.
Now, if the code you wanted to write has to be executed on VC2 before you pop it, then you can use in VC2:
-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([[viewController class] isSubclassOfClass:[VC1 class]])
NSLog(@"We are going back to VC1");
}
This is a UINavigationController delegate method so VC2 would have to adopt that protocol by adding UINavigationControllerDelegate at the end of its @interface line in the .h file:
@interface VC2 : UIViewController <UINavigationControllerDelegate>
And you would have to set VC2 as delegate for the UINavigationController so you have to put in viewDidLoad of VC2:
self.navigationController.delegate=self;
You will obviously also need to import VC1.h file into VC2 since you are referring to it in the delegate method code above.
Hope this helps