Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab Bar Application With Navigation Controller

Tags:

iphone

tabbar

Once you have a tab bar in a XIB, the easiest way to approach this is to drag a UINavigationController object over from the Library window (looks like a left nav bar button on a gold background) into the Tree View for your tab bar (the text only view, not the GUI). Place the navigation controller inside the tab bar controller, then drag your existing view controller inside the navigation controller.

When you go to view that tab you should then see a navigation bar on the top of it... if you are loading the navigation controller from another xib, you'll modify the nav bar in the tab bar xib.


This is how to add the NavigationController programmatically (e.g. in you AppDelegate)

  UIViewController  *viewController1, *viewController2;

    viewController1 = [[[UIViewController alloc] initWithNibName:@"FirstViewController_iPhone" bundle:nil] autorelease];
    UINavigationController *navigationcontroller = [[[UINavigationController alloc] initWithRootViewController:viewController1] autorelease];

    viewController2 = [[[UIViewController alloc] initWithNibName:@"SecondViewController_iPhone" bundle:nil] autorelease];

    self.tabBarController = [[[UITabBarController alloc] init] autorelease];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:navigationcontroller, viewController2, nil];

If you have a tableview in the Viewcontroller1 you can access the Navigationcontroller by using self.navigationController e.g. in the didSelectRowAtIndexPath to open a DetailView

eg.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

In this example the detailViewController inits with a NIB file, which adds a navigation bar with a back button. But if you init the detailViewController programmatically aswell, you can add an action (GoBack) to a UIBarButtonItem to remove the detailViewController from its navigationcontroller.

-(void) GoBack
{    
    [self.navigationController popViewControllerAnimated:YES];
}

I realized this is late, but this question is #1 on google results today and so I figured I'd add an answer. There is a great youtube video tutorial by O'Reilly that walks you through a tabbar + navigation controller app. Check it out here: http://www.youtube.com/watch?v=LBnPfAtswgw


The way to think about it is this:

You want each tab to have a navigation controller. Then, each nav controller needs to have a root view controller and a loaded Nib.

So, in IB, add nav controllers for each of your tabs. Then, configure each nav controller to have the appropriate root view controller and Nib.