Question

I had a navigation controller based application. And I decided to use tab bars in my application.

When the user presses at a certain tab bar item I want to display a certain view controller - and I want programmatically in my code choose which one to display.

I tried to add in the Interface Builder a navigation controller into my tab bar, but viewWillAppear of its view controller is not being called.

How can I implement this feature?

Was it helpful?

Solution

I don't know if it's the "right way", but here's how I usually do this with three tabs.

- (void)initControls {
    // Create the window.
    [self setWindow:[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]];

    // Create Tab Bar.
    tabCon = [[UITabBarController alloc] init];

    // Local array variable that holds the viewcontrollers.
    // Capacity corresponds to the number of VC's
    NSMutableArray *localVCArray = [[NSMutableArray alloc] initWithCapacity:3];

    MyFirstViewController *oneViewController = [[MyFirstViewController alloc] init];
    UINavigationController *oneNavCon = [[UINavigationController alloc] initWithRootViewController:oneViewController];
    [localVCArray addObject:oneNavCon];
    [oneViewController release];
    [oneNavCon release];

    MySecondViewController *twoViewController = [[MySecondViewController alloc] init];
    UINavigationController *twoNavCon = [[UINavigationController alloc] initWithRootViewController:twoViewController];
    [localVCArray addObject:twoNavCon];
    [twoViewController release];
    [twoNavCon release];

    MyThirdViewController *threeViewController = [[MyThirdViewController alloc] init];
    UINavigationController *threeNavCon = [[UINavigationController alloc] initWithRootViewController:threeViewController];
    [localVCArray addObject:threeNavCon];
    [threeViewController release];
    [threeNavCon release];

    // Set the tab bars array of view controllers to the localVCArray
    [[self tabCon] setViewControllers:localVCArray animated:YES];

    // Release the localVCArray, all of its contents are now retained by tabCon.
    [localVCArray release];

    // Add controls to window and show.
    [window addSubview:[tabCon view]];
    [window makeKeyAndVisible];
}

In the init method each viewController you can do something like:

[[self tabBarItem] setImage:[dataSource tabConImg]];
[[self tabBarItem] setTitle:[dataSource name]];
[[self navigationItem] setTitle:[dataSource navConName]];

To set the icon used in the tab bar, the title in the tab bar, and the title of you navigation item.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top