biggreentree
biggreentree

Reputation: 1933

Adding NavigationController to TabBar based app programmatically

I have 6 viewControllers in a customTabBar based app. TabbBar added programmatically. Now I'd like to add a navigationcontroller in order to push detail view controllers getting benefits from navigationBar, but keeping the TabBar below as main way to navigate in the entire app.

with this code I obtain the first uiviewcontroller "FirstVC" with navigation bar on screen, but I cannot "push" the detail "FirstDetail1VC" view controller(s) from a test button

in my AppDelegate:

window = UIWindow(frame: UIScreen.main.bounds)

let myTabController = CustomTabbarController()

window?.rootViewController = myTabController
window?.makeKeyAndVisible()

in my1VC (giving message "cannot push UINavigationController") :

func showNextVc() {

    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    if let newViewController = storyboard.instantiateViewController(withIdentifier: "FirstDetail1VC") as? FirstDetail1VC {

        let navigator = MyMainNavController {
            navigator.pushViewController(newViewController, animated: true)
        }
    }
}

after update in CustomTabbarController:

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let my1VC = storyboard.instantiateViewController(withIdentifier: "FirstVC")
let my2VC = storyboard.instantiateViewController(withIdentifier: "SecondVC")
let my3VC = storyboard.instantiateViewController(withIdentifier: "ThirdVC")
let my4VC = storyboard.instantiateViewController(withIdentifier: "FourthVC")
let my5VC = storyboard.instantiateViewController(withIdentifier: "FifthVC")
let my6VC = storyboard.instantiateViewController(withIdentifier: "SixthVC")

my2VC.tabBarItem = UITabBarItem(title: "second", image: nil, selectedImage: nil)
my3VC.tabBarItem = UITabBarItem(title: "third", image: nil, selectedImage: nil)
my4VC.tabBarItem = UITabBarItem(title: "fourth", image: nil, selectedImage: nil)
my5VC.tabBarItem = UITabBarItem(title: "fifth", image: nil, selectedImage: nil)
my6VC.tabBarItem = UITabBarItem(title: "sixth", image: nil, selectedImage: nil)

let controllers = [my1VC, my2VC, my3VC, my4VC,my5VC, my6VC]


// if I use this one, text titles appears on tab bar, but cannot use navigation controller
viewControllers = controllers

// if I use this I have the navigation controlelr working but     
tabBarbuttons not showing text title
// self.viewControllers = controllers.map {
// UINavigationController(rootViewController: $0)
// }

Upvotes: 0

Views: 1153

Answers (1)

Jay Patel
Jay Patel

Reputation: 2740

Assign UINavigationController to each UIViewController when set array of all ViewControllers.

//Add NavigationController to all VC
viewControllers = [start, my1VC, my2VC, my3VC, my4VC,my5VC, my6VC].map {
    UINavigationController(rootViewController: $0)
}

Upvotes: 2

Related Questions