在推送viewcontroller时,navigationController是nil

时间:2018-04-24 12:19:00

标签: ios xcode navigationcontroller

有三个viewControllerMainViewController ViewControllerBViewControllerC。 应用启动时会加载MainViewController

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];

    MainViewController * main = [[MainViewController alloc]init];
    UINavigationController * navigationController = [[UINavigationController alloc]initWithRootViewController:main];
    self.window.rootViewController = navigationController;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    return YES;       
}

button上有一个MainViewController,现有ViewControllerB

UIViewController *rootViewController = [[UIApplication sharedApplication].keyWindow rootViewController];
ViewControllerB * vcb=[[ViewControllerB alloc] init];
[rootViewController presentViewController:vcb animated:YES completion:nil];

出现ViewControllerB后,点击按ViewController C按钮。 但navigationControllernil。它无法推送ViewControllerC

[self.navigationController pushViewController:vcC animated:YES];

1 个答案:

答案 0 :(得分:4)

  1. 您拥有MainViewController( mvc ),它嵌入在 NavigationController ;

  2. 然后,在 mvc 上,您有以下代码:

    [rootViewController presentViewController:vcb animated:YES completion:nil];

    您正在当前的ViewController上调用presentViewController以模态方式呈现下一个ViewController,在本例中为ViewControllerB( vcb );

  3. 最后,您尝试访问ViewControllerB( vcb )中的 NavigationController 以推送ViewControllerC( vcc ),以下代码:

    [self.navigationController pushViewController:vcC animated:YES];

  4. 问题是 vcb 不知道 NavigationController ,因为presentViewController在现有导航堆栈之外以模态方式呈现视图控制器。因此,在 vcb 中产生 nil NavigationController

    您可以参考https://stackoverflow.com/a/14233252/9323816了解更多信息。