Reputation: 57
I have three UIViewControllers. I am navigating to VC3 from VC1. I want to navigate to VC2 if I click on cancel or done button from VC3.
I have added the VC2 controller to navigation stack programmatically.
DocListViewController *temp1 = [[DocListViewController alloc] initWithNibName:@"DocListViewController" bundle:nil];
[self.navigationController addChildViewController: temp1];
for (UIViewController *controllers in self.navigationController.viewControllers) {
if([controllers isKindOfClass: [DocListViewController class]]) {
DocListViewController *VC2ViewController = (DocListViewController*)controllers;
[self.navigationController popToViewController:VC2ViewController animated:YES];
}
}
Upvotes: 2
Views: 97
Reputation: 1423
What you are doing wrong here is adding it as child view controller,addChildViewController
as it as a child of the current view controller does not add it in the navigation stack.
You need to insert the controller in you navigation stack before doing popToViewcontroller
.
VC2 *temp1 = [[VC2 alloc] initWithNibName:@"DocListViewController" bundle:nil];
NSMutableArray *vcArray = [NSMutableArray arrayWithArray:self.navigationController.viewControllers] ;
[vcArray insertObject:temp1 atIndex:1]; // ** This index is `1` assuming you only have 2 controllers and we are pushing it in the middle,
// if you have many vc in navigation stack and just want to insert a new vc just before your current vc go with this:
/*
[vcArray insertObject:temp1 atIndex:vcArray.count - 2];
*/
self.navigationController.viewControllers = vcArray;
/* --- ** This part is also not needed:
for (UIViewController *controllers in self.navigationController.viewControllers) {
if([controllers isKindOfClass: [DocListViewController class]]) {
[self.navigationController popToViewController: controllers animated:YES];
}
}
*/
[self.navigationController popViewControllerAnimated:true];
Also: you don't need VC2 *VC2ViewController = (VC2*)controllers;
inside the if
block as you only need a UIViewController
type object for pop-ing.
I have just edited your code, get the project reference below
Edit: Adding GitHub link for better reference: PlayingWithNavigation
Upvotes: 1
Reputation: 3727
UIViewController *vc2 = [[UIViewController alloc] init];
UIViewController *vc3 = [[UIViewController alloc] init];
[self.navigationController pushViewController:vc2 animated:NO];
[self.navigationController pushViewController:vc3 animated:YES];
Try this.
Upvotes: 0
Reputation: 381
You can navigate to VC2 using pushviewContoller
NSString * storyboardName = @"Main";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
VC2 * VC2View = [storyboard instantiateViewControllerWithIdentifier:@"VC2ID"]; // "VC2ID" is the storyboard Id of your view controller
[self.navigationController pushViewController:VC2View animated:YES];
Upvotes: 0