self.navigationController为null [英] self.navigationController is null
问题描述
在我的viewcontroller中,我有一个按钮,按下按钮,输入navigationController,我的代码如下:
in my viewcontroller,I have a button,when press the button,entry the navigationController,my code like:
-(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,如何解决这个问题?谢谢。
but I can see the self.navigationController is null,how to solve this problem?thank you.
更新:
- (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 <仅当视图控制器位于导航控制器的导航堆栈中时,视图控制器的/ em>属性才会返回有效的导航控制器对象。可以通过以下方式将视图控制器添加到导航堆栈。
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.
-
使用 initWithRootViewController:方法将视图控制器作为导航控制器的rootViewController > UINavigationController
By making the view controller the rootViewController of a navigation controller using initWithRootViewController: method of UINavigationController
使用 UINavigationController 的 pushViewController:方法推送视图控制器。
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.
编辑:(在didFinishLaunchingWithOptions:代码添加到问题后):
(After the didFinishLaunchingWithOptions: code added to the question):
将 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
}
这篇关于self.navigationController为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!