How to embed a tab bar controller inside a navigation controller?

Generated on 7/31/2024

1 search

To embed a tab bar controller inside a navigation controller, you can follow these steps:

  1. Create a UITabBarController instance: This will be the main controller that holds your tab bar.

  2. Create instances of the view controllers you want to include in the tab bar: These view controllers will be the individual tabs.

  3. Embed each view controller in a UINavigationController: This allows each tab to have its own navigation stack.

  4. Set the view controllers of the UITabBarController: Assign the array of navigation controllers to the tab bar controller.

Here is a sample code snippet in Swift:

import UIKit

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .red
        self.title = "First"
    }
}

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blue
        self.title = "Second"
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        
        let firstVC = FirstViewController()
        let secondVC = SecondViewController()
        
        let firstNavController = UINavigationController(rootViewController: firstVC)
        let secondNavController = UINavigationController(rootViewController: secondVC)
        
        let tabBarController = UITabBarController()
        tabBarController.viewControllers = [firstNavController, secondNavController]
        
        window?.rootViewController = tabBarController
        window?.makeKeyAndVisible()
        
        return true
    }
}

In this example:

  • FirstViewController and SecondViewController are the view controllers that will be displayed in the tabs.
  • Each view controller is embedded in a UINavigationController.
  • These navigation controllers are then assigned to the viewControllers property of the UITabBarController.

For more detailed information on how to enable the sidebar with UITabBarController in UIKit, you can refer to the session Elevate your tab and sidebar experience in iPadOS.