Showing a modal view with a navigation bar

This took me about an hour to figure out so I’m blogging it. I was interested to show a modal view with a navigation bar at the top. I wanted the navigation bar so as to put a descriptive title for the modal view. I read one solution here which is to use a label to show the title. But I kind of like the look of navigation bars at the top. Besides, the HIG from Apple shows a modal view with a navigation bar so I think showing the title this way is an accepted approach.

I added a navigation bar in the Xib file but the navigation bar was not showing in the modal view. I fiddled with some other options with no luck. Thanks to this discussion which showed me the right way.

What I did was change my original code,

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

to this,

DatePickerViewController *datePickerViewController = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
 UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:datePickerViewController];
[self presentModalViewController:navigationController animated:YES];

and my modal view has,

- (void)viewDidLoad {
 [super viewDidLoad];
 self.title = @"Set date and time";

I still don’t understand why adding the navigation bar in the Xib file did not work. Maybe there is something more fundamental I am missing. I’ve spent too much time on this already though, time to move on!

5 thoughts on “Showing a modal view with a navigation bar

  1. Thanks! I was was looking for this info. I worked great. You have saved me some time

  2. Thanks – this is exactly what I was looking for!

    I guess when something is presented modally, the navigationController gets lost so it needs a new instance of it.

  3. Thanks a lot! I was pouring over several articles/forums over “why my modal view is never displaying the navigation bar” and i got the answer in this article.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>