jkigel
jkigel

Reputation: 1592

UIViewController's navigationController is nil

I'm trying to access navigationController from UIViewController, for some reason it equals nil

AppDelegate:

self.mainViewController = [[MainViewController alloc] init];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.mainViewController];
self.window.rootViewController = self.navigationController;

MainViewController:

 MyViewController *myViewController = [[MyViewController alloc] init];
[self.navigationController presentModalViewController:myViewController animated:YES];

Anyone has encountered this problem?

Thanks!

Upvotes: 7

Views: 5503

Answers (3)

chongsj
chongsj

Reputation: 25

Create UINavigationController assign your viewcontroller to its root.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: myViewController];
[self presentViewController:navController animated:YES completion:nil];

Upvotes: 1

tooluser
tooluser

Reputation: 1542

You're doing much of the correct code, but not all in the correct places. You're correct that a UINavController should be initialized with a view controller. However, in the code you sent, MainViewController's init method is complete before the nav controller is initialized.

This is due to the fact that you really shouldn't be having the MainViewController decide when to present itself. It should be initialized and presented by something outside itself - the AppDelegate, in this case.

AppDelegate:

MainViewController *mvc = [[MainViewController alloc] init];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
self.window.rootViewController = self.navigationController;

If you then need MainViewController to present something modally, you should do it in viewWillAppear: or viewDidLoad:, not in its init method. Alternatively, create a public method on MainViewController (showMyModal) that the app delegate can call.

Upvotes: 2

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

A UIViewController may not have a UINavigationController.
The navigation controller owns some controller only if you set it expicitly:

[yourNavController setViewControllers: @[ yourViewController1, ... , yourViewControllerN] ];

Upvotes: 0

Related Questions