可能重复:
Why can't I push a new view controller onto the current view?
Why is my new view controller not appearing?
我需要从我的navigationController推送我的视图控制器,但在完成一个NSLog语句以找出为什么没有显示以下代码时,我意识到它返回null:
-(IBAction)doChangePasscode{
NSLog(@"Change Passcode Screen Loaded!");
ChangePasscode *cpscreen = [[ChangePasscode alloc] initWithNibName:@"ChangePasscode" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:cpscreen animated:YES];
NSLog(@"%@",self.navigationController);
}
为什么会这样?除了(null)之外,我该怎么做才能返回正确的值?
答案 0 :(得分:1)
就像每个人都在此和 Why is my new view controller not appearing? 中解释的那样,您需要先拥有导航控制器。使用该导航控制器推送视图控制器,然后视图控制器将不再为navigationController
属性设置为空。
在此示例中,someSecondViewController
将是您上面代码中的self
:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
RootViewController *rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
self.nav = [[[UINavigationController alloc] initWithRootViewController:rootViewController] autorelease];
[rootViewController release];
[self.window addSubview:nav.view];
[self.window makeKeyAndVisible];
}
- (void)someOtherMethod {
SecondViewController *someSecondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self.nav pushViewController:someSecondViewController animated:YES];
[someSecondViewController release];
}
请查看以下内容:
View Controller Programming Guide for iOS
UINavigationController Docs
UIViewController Docs
答案 1 :(得分:0)
我假设你的意思是返回nil,这意味着viewController没有导航控制器,你可以通过让你的viewController成为新创建的UINavigationController的根来解决它:
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myRootViewController];
然后对于myRootViewController,self.navigationController将返回导航控制器。
我假设viewController是你应用中的第一个,所以你想在你的appDelegate上有这个:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
MyViewController *viewController = [[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil] autorelease];
UINavigationController *myNavController = [[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];
self.window.rootViewController = myNavController;
[self.window makeKeyAndVisible];
return YES;
}
然后,如果IBAction在MyViewController上,则self.navigationController将返回导航控制器而不是nil。
希望有所帮助。