Search code examples
iosswiftuikit

How to embed a view in a navigation controller programmatically?


I have 3 view controllers in a UITabBarController. In only one view controller I would like to place it in a navigation controller. What is the proper way of doing this so that only one view controller has a Navigation Controller? I would like aController to be in a navigation controller.

import UIKit

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let mController = MViewController()
        mpController.tabBarItem = UITabBarItem(title: "view1", image: UIImage(named: "viewoneimage"), tag: 0)



        let inputController = InputViewController()
        inputController.tabBarItem = UITabBarItem(title: "Input", image: UIImage(named: "plus"), tag: 1)

        let aController = ATableViewController()
        aController.tabBarItem = UITabBarItem(title: "custom", image: UIImage(named: "person.fill"), tag: 2)
        let navController = UINavigationController()
//        aController.navigationController = navController


        viewControllers = [mController, inputController, aController, navController]
        // Do any additional setup after loading the view.
    }




}

Solution

  • You must embend your UIViewController inside the Navigation Controllers and initialize your tab menu with your Navigation Controllers.

    Also for each tab you will have different Navigation Controller

    Your code should look like that.

    import UIKit
    
    class TabBarController: UITabBarController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let mController = MViewController()
            mpController.tabBarItem = UITabBarItem(title: "view1", image: UIImage(named: "viewoneimage"), tag: 0)
            let inputController = InputViewController()
            inputController.tabBarItem = UITabBarItem(title: "Input", image: UIImage(named: "plus"), tag: 1)
            let aController = ATableViewController()
            aController.tabBarItem = UITabBarItem(title: "custom", image: UIImage(named: "person.fill"), tag: 2)
            let navMController = UINavigationController(rootViewController: mpController)
            let navInputController = UINavigationController(rootViewController: inputController)
            let navaController = UINavigationController(rootViewController: aController)
            viewControllers = [navMController, navInputController, navaController]
        }
    }