Embedding a Table View Controller Inside a Tab Bar Controller Using Xcode

Table View Controller Inside Tab Bar Controller

Problem

You want to create a table view controller that is embedded inside a tab bar controller.

Solution

To solve this problem, you need to create a UITabBarController and add two view controllers to it: one for the main screen and another for the navigation controller with the table view. You also need to set the tabBarStyle property of the tab bar controller to UIibarStyleDefault.

Code

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

@interface TableViewController : UITableViewController

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

@end

int main(int argc, char * argv[]) {
    @autoreleasepool {
        // Create tab bar controller
        UITabBarController *tabBarController = [[UITabBarController alloc] init];

        // Create view controllers for each screen
        UIViewController *viewControllerOne = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
        UITableViewController *viewControllerTwo = [[TableViewController alloc] initWithNibName:@"TableViewController" bundle:nil];

        // Create navigation controller with table view and add it to the view controller
        UINavigationController *myNavigationController = [[UINavigationController alloc] initWithRootViewController:viewControllerTwo];

        // Add view controllers to the tab bar controller
        NSArray* controllers = [NSArray arrayWithObjects:viewControllerOne, myNavigationController, nil];
        tabBarController.viewControllers = controllers;

        // Set tab bar style to default
        tabBarController.tabBarStyle = UIBarStyleDefault;

        // Create window and set root view controller
        UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        window.rootViewController = tabBarController;
        window.makeKeyAndVisible();

        // Run application
        [appDelegate applicationDidFinishLaunching:nil];
    }
    return 0;
}

Explanation

In this example, we create a UITabBarController and add two view controllers to it: one for the main screen (ViewController) and another for the navigation controller with the table view (TableViewController). We also set the tabBarStyle property of the tab bar controller to UIibarStyleDefault. Finally, we create a window and set the root view controller to the tab bar controller.

Note

Make sure to replace "ViewController" and "TableViewController" with your actual nib names.


Last modified on 2024-05-23