Ios – How to add a Navigation Controller with Interface Builder

interface-builderiosiphoneobjective cuinavigationcontroller

1. Step: Create a new UIViewController:
– Xcode -> New File… -> Cocoa Touch Class -> UIViewController
– Name: MyViewController

2. Step: Drag and drop a "Navigation Controller" (UINavigationController) from the Library to MyViewController.xib

alt text

3.Step: I'm sure, I have to do something to connect the Navigation Controller correctly, isn't it?

4.Step: Try to start the new View Controller as a modal dialog:

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
NSLog(@"navContr: %@", myViewController.navigationController);
[self.navigationController presentModalViewController: myViewController animated:YES]; 

Result: "navContr: nil"

5.Step: You can see the new modal view (MyViewController), but there's no NavigationController and no UINavigationBar.

Thank you very much for your help!


UPDATE 1:

6.Step: I set a new UIViewController (ViewNavi2) as "Root View Controller":
alt text

7.Step: I define a IBOutlet UINavigationController *navigationController in the class MyViewController and configure the xib: Navigation Controller -> Connections -> Referencing Outlets

But my Navigation Controller is still nil 🙁

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
NSLog(@"navContr: %@", myViewController.navigationController);
// -> "navContr: nil"

Best Answer

I also wanted to include the navigation controller in the NIB file, but all that the Apple documentation said was that it is "not optimal" without actually explaining how to do it. I wanted my main tabbed window to call up a modal window containing the typical navigation controls without defining the navigation controller programmatically. I'll share how I did it.

Your code was very similar to mine, as I also defined an IBOutlet UINavigationController *navigationController in MyViewController. From Interface Builder, I simply defined my view in the root view controller and set the File's Owner->view to that view definition.

And similarly to your code, I did the following in my parent window:

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[self presentModalViewController:myViewController animated:YES];

(I am calling presentModelViewController on self, I don't know why you had self.navigationController.) When I tested this, the result was that my view was loaded from the NIB file, but the navigation bar was missing. One more line of code in MyViewController fixed this:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setView:myNavigationController.view];

}

All I am doing here, is setting MyViewController's view to point to myNavigationController.view, which contains everything that was defined in the NIB file, including the navigation controller.