Programmatically add UINavigationController in UIViewController

joshholat picture joshholat · Dec 9, 2010 · Viewed 32k times · Source

I currently have a view set up as the following:

@interface BlogViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    UITableView *mainTableView;
}

@property (nonatomic, retain) UITableView *mainTableView;

As you can see, it has a UITableView inside of it that I load all of my data to. However, when I call the following function:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SingleBlogViewController *viewController = [[SingleBlogViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
    //[self presentModalViewController:viewController animated:YES];
    [viewController release];
}

nothing happens. For some reason my UITableView inside of my UIViewController isn't pushing the view. Is this because it isn't a UITableViewController? I tried changing it to that, and it still didn't work.

Am I missing something here?

Answer

David Blevins picture David Blevins · Jan 19, 2011

I found the first parts of this blog post useful for showing how to create and use a UINavigationController programmatically without Interface Builder.

Some of the things I wish the docs and tutorials would have stressed to me:

  • When you create the UINavigationController you get a UIView and UINavigationBar for free (i.e. you don't need to separately add them and figure out how to hook them together).

  • You add the myUINavigationController.view property as the "main" view and then push/pop UIViewControllers onto the UINavigationController and they will automatically show up as visible in the myUINavigationController.view UIView.

  • When you push a UIViewController onto a UINavigationController, the UIViewController.navigationController is filled in. If you haven't pushed the view onto the navigation controller, I'm guessing that property is empty.

  • The time/place to programmatically add buttons to the UINavigationBar is not when and where you construct the UINavigationController, but rather by the individual UIViewControllers when they are loaded as you push onto the UINavigationController.

  • I only had to add a "Done" button to the UINavigationController's UINavigationBar in the viewDidLoad method of the first UIViewController pushed onto the UINavigationController. Any UIViewController I pushed on top of that first view automatically had a "back" button in the to navigate to the covered up UIViewController.

  • If you set the title property of your UIViewController before you put it on the UINavigationController's stack. The UINavigationBars title will be the title of your view. As well any "back" buttons will automatically name the view you are returning to instead of generically saying "back".