UITabBar with UINavigationController in code

2019-08-09 03:45发布

问题:

I've currently got a UITabBar with 5 screens calling UIViews. That part works fine but I want to put in a UINavigationController in a couple of them. I have found a few tutorials that work fine but all of them implement it in IB and I want to avoid that if possible.

I'm lost as to where to implement the UINavigationController, should I do it in the App Delegate with the UITabBar and call the navigation controller from the UIView or should I create it in the UIView class?

I've tried about 8 different ways and always ends up with either the Navbar not working, no nav bar at all or the app crashing.

Currently I create the tab bar like this:

tabBarController = [[UITabBarController alloc] init];
ScreenA *screenA = [[ScreenA alloc] initWithNibName:@"ScreenA" bundle:nil];
//more here
tabBarController.viewControllers = [NSArray arrayWithObjects:screenA, ...., nil];
[window addSubview:tabBarController.view];

And in the initWithNibName I have this:

self.title = @"Screen A";
self.tabBarItem.image = [UIImage imageNamed:@"someImage.png"];

回答1:

Ok, do it like this...

    tabBarController = [[UITabBarController alloc] init];    

searchTableViewController = [[SearchTableViewController alloc] init];
    UINavigationController *searchTableNavController = [[[UINavigationController alloc] initWithRootViewController:searchTableViewController] autorelease];
[searchTableViewController release];                                                              

searchMapViewController = [[SearchMapViewController alloc] init];   
UINavigationController *mapTableNavController = [[[UINavigationController alloc] initWithRootViewController:searchMapViewController] autorelease];
[searchMapViewController release];                                                    


tabBarController.viewControllers = [NSArray arrayWithObjects:searchTableNavController, mapTableNavController, nil];