self.navigationController is null

前端 未结 3 742
温柔的废话
温柔的废话 2021-01-04 08:24

in my viewcontroller,I have a button,when press the button,entry the navigationController,my code like:

-(IBAction)ShangHaiButtonPressed:(id)sender{
    mark         


        
3条回答
  •  鱼传尺愫
    2021-01-04 09:22

    The navigationController property of a view controller will return a valid navigation controller object only if the view controller is in a navigation controller's navigation stack. A view controller can be added to a navigation stack in the following ways.

    1. By making the view controller the rootViewController of a navigation controller using initWithRootViewController: method of UINavigationController

    2. By pushing the view controller using pushViewController: method of UINavigationController.

    Make sure your view controller is added to the navigation stack in any of the above ways.


    EDIT: (After the didFinishLaunchingWithOptions: code added to the question):

    Change the didFinishLaunchingWithOptions: method to this,

    - (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 (version):

    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
    }
    

提交回复
热议问题