navigationController为null

navigationController为null

在我的视图控制器中,我有一个按钮,当按下该按钮时,输入navigationController,我的代码如下:

-(IBAction)ShangHaiButtonPressed:(id)sender{
    marketviewcontroller = [[MarketViewController alloc]initWithNibName:@"MarketViewController" bundle:nil];
    NSLog(@"%@",self.navigationController);
    [self.navigationController pushViewController:marketviewcontroller animated:YES];
    [marketviewcontroller release];
}


但是我可以看到self.navigationController为null,如何解决这个问题?谢谢。

更新:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    _switchviewcontroller = [[SwitchViewController alloc]initWithNibName:@"SwitchViewController" bundle:nil];
    [self.window addSubview:_switchviewcontroller.view];
    [self.window makeKeyAndVisible];
    return YES;
}

最佳答案

仅当视图控制器位于导航控制器的导航堆栈中时,视图控制器的navigationController属性才会返回有效的导航控制器对象。可以通过以下方式将视图控制器添加到导航堆栈。


通过使用initWithRootViewController:UINavigationController的方法使视图控制器成为导航控制器的rootViewController
通过使用UINavigationController的pushViewController:方法推送视图控制器。


确保以上述任何一种方式将视图控制器添加到导航堆栈中。



编辑:(在didFinishLaunchingWithOptions:代码添加到问题之后):

将didFinishLaunchingWithOptions:方法更改为此,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    _switchviewcontroller = [[SwitchViewController alloc]initWithNibName:@"SwitchViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:_switchviewcontroller];
    [self.window addSubview:navController.view];
    [navController release];
    [self.window makeKeyAndVisible];
    return YES;
}


Swift 4(版本):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    switchviewcontroller = SwitchViewController(nibName: "SwitchViewController", bundle: nil)
    let navController = UINavigationController(rootViewController: switchviewcontroller)
    window.addSubview(navController.view)
    window.makeKeyAndVisible()
    return true
}

07-27 14:31