How to create a UITabBarController in code

- by

Tab Bar Controllers are setup with an array of view controllers. We’ll create those first, then we simply give said array to our tab bar controller.

In this example, this is a subclass of UITabBarController:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // let's create several View Controllers with different colours each
    ViewController *vc1 = [self createViewcontrollerWithColor:[UIColor redColor]];
    ViewController *vc2 = [self createViewcontrollerWithColor:[UIColor greenColor]];
    ViewController *vc3 = [self createViewcontrollerWithColor:[UIColor blueColor]];
    ViewController *vc4 = [self createViewcontrollerWithColor:[UIColor yellowColor]];
    
    vc1.title = @"One";
    vc2.title = @"Two";
    vc3.title = @"Three";
    vc4.title = @"Four";

    NSArray *controllers = @[vc1, vc2, vc3, vc4];
    
    // populate our tab bar controller with the above
    [self setViewControllers:controllers animated:YES];
}

Note that I’m also setting the title property of each view controller. This is displayed as the tab bar text and is left blank if not specified. To override this behaviour and/or specify graphics, set the UITabBarItem of each individual view controller.

The method that creates the view controllers is very straightforward: in this example I have a single ViewController in my storyboard (with a Storyboard ID of “PlainViewController”). All we do here is specify a funky background colour to tell them apart:

- (ViewController *)createViewcontrollerWithColor:(UIColor *)color {

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ViewController *newViewcontroller = [storyboard instantiateViewControllerWithIdentifier:@"PlainViewController"];
    newViewcontroller.backgroundColor = color;
    
    return newViewcontroller;
    
}

Note that the tab bar configuration is not set in stone: you can switch out the view controllers on the fly by calling the setViewcontrollers method again, passing in new content.

Here’s a full working demo project that show it all in action:

and the class reference:



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.