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!
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.
Create UINavigationController assign your viewcontroller to its root.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: myViewController];
[self presentViewController:navController animated:YES completion:nil];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With