如何导航到NavigationStack中不存在的UIViewController

时间:2018-07-31 06:36:35

标签: ios objective-c uinavigationcontroller

我有三个UIViewControllers。我正在从VC1导航到VC3。如果要单击VC3中的“取消”或“完成”按钮,我想导航到VC2。

我已通过编程将VC2控制器添加到导航堆栈中。

    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];            
      }
    }

3 个答案:

答案 0 :(得分:1)

您在这里做的错误是将其添加为子视图控制器addChildViewController,因为它作为当前视图控制器的子视图并未将其添加到导航堆栈中。

enter image description here

执行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];

此外:您不需要VC2 *VC2ViewController = (VC2*)controllers;if块中,因为您只需要一个UIViewController类型的对象即可弹出。

我刚刚编辑了您的代码,请在下面获取项目参考

编辑: 添加GitHub链接以获得更好的参考: PlayingWithNavigation

答案 1 :(得分:0)

您可以使用pushviewContoller导航到VC2

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

答案 2 :(得分:0)

    UIViewController *vc2 = [[UIViewController alloc] init];
    UIViewController *vc3 = [[UIViewController alloc] init];

    [self.navigationController pushViewController:vc2 animated:NO];
    [self.navigationController pushViewController:vc3 animated:YES];

尝试一下。