Search code examples
iosobjective-cuitabview

How can I create a tab view programmatically on iOS


For an iPhone app how can I create a tab view programmatically, preferably in Objective-C?


Solution

  • It's quite simple to create a UITabBar via the UITabBarController. The following example should work within your AppDelegate class.

    App Delegate Interface

    Firstly, within the interface, we'll define our UITabBarController.

    UITabBarController *tabBarController;
    

    App Delegate Implementation

    Then, within the implementation file's application:didFinishLaunchingWithOptions: method, we'll then initialise our tab bar controller.

    // Initialise our tab bar controller
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    

    Next, you need to create the view controllers that you want to add to the tab bar controller. We'll need to add some information into these to set the tab's title/icon, but I'll come back to that at the end.

    // Create your various view controllers
    UIViewController *testVC = [[TestViewController alloc] init];
    UIViewController *otherVC = [[OtherViewController alloc] init];
    UIViewController *configVC = [[ConfigViewController alloc] init];
    

    As the setViewControllers:animated: method requires an array of view controllers, we'll add our view controllers to an array and then release them. (As the NSarray will retain them.)

    // Put them in an array
    NSArray *viewControllers = [NSArray arrayWithObjects:testVC, otherVC, configVC, nil];
    [testVC release];
    [otherVC release];
    [configVC release];
    

    Then simply provide the UITabBarController with the array of view controllers and add it to our window.

    // Attach them to the tab bar controller
    [tabBarController setViewControllers:viewControllers animated:NO];
    
    // Put the tabBarController's view on the window.
    [window addSubview:[tabBarController view]];    
    

    Finally, make sure you call [tabBarController release]; within your dealloc method.

    View Controller Implementation

    Inside each of your view controllers, you'll also want to set the title and icon for the tab within the init method as follows:

    // Create our tab bar item
    UITabBarItem *tabBarItem = [self tabBarItem];
    UIImage *tabBarImage = [UIImage imageNamed:@"YOUR_IMAGE_NAME.png"];
    [tabBarItem setImage:tabBarImage];
    [tabBarItem setTitle:@"YOUR TITLE"];