Reputation: 47
I have a problem that my iOS app has several ViewControllers
.
For example: ViewControllers named like A
, B
, C
. A
jumped to B
with pushViewController
, B
jumped to C
with presentViewController
, C
jumped to D
with presentViewController
and so on.
If the current ViewController is Z
or some other ViewController, how can I jump back to A
directly?
Upvotes: 0
Views: 144
Reputation: 5799
Try Below code. It will work for all cases :
for (UIViewController *controller in self.navigationController.viewControllers)
{
if ([controller isKindOfClass:[nameOfYourViewControllerYouWantToNavigate class]])
{
if(controller.isBeingPresented)
[controller.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
else
[self.navigationController popToViewController:controller animated:YES];
break;
}
}
Upvotes: 1
Reputation: 9589
Whatever you want to go back to A ViewController from any other view controller, first you have to set that as RootViewController
. If you use XIB you must set as root in app delegate didFinishLaunchWithOptions
method. If you use storyboard you should set NavigationController
in storyboard and set AViewController as ROOT using control+drag(mouse).
I work in a project which has lot of view controllers. It has pushViewController
and PresentViewControllers
also I set A asRootViewController
. So I can return from any view controller to RootViewController.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
AViewController *aVC = [[AViewController alloc]initWithNibName:@“AViewController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:aVC];
self.window.rootViewController = aVC;
[navController setNavigationBarHidden:YES];
self.window.backgroundColor = [UIColor clearColor];
[self.window makeKeyAndVisible];
return YES;
}
For going to AViewController from any other view controller
- (IBAction)actionGoBack:(id)sender
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
Upvotes: 0
Reputation: 761
[[self navigationController] popToRootViewControllerAnimated:YES];
It will pop your viewcontroller to Root controller.
Upvotes: 1
Reputation: 586
For the view controllers show by pushViewController
, you can get rootViewController via [self.navigationController.viewControllers objectAtIndex:0]
Others shown by presentViewController
, you can get parent view controller via self.presentingViewController
Upvotes: 0