Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use both navigation controller and tab bar

I use navigation controller to push my views. Like this:

func showDetailForCategory(product: Category){

    let storyBoard = UIStoryboard(name: "Main", bundle:nil)
    let categoryViewController =  storyBoard.instantiateViewController(withIdentifier: "categoryDetail") as! CategoryViewController
    
    categoryViewController.categoryId = product.id
    self.navigationController?.pushViewController(categoryViewController, animated:true)
    
}

It works just fine. But i want to use toolbar too. My AppDelegate is like below

    let layout = UICollectionViewFlowLayout()
    let featuredAppsController = FeaturedAppsController(collectionViewLayout: layout)
    window?.rootViewController = UINavigationController(rootViewController: featuredAppsController)
    
    let vc1 = featuredAppsController
    vc1.tabBarItem.title = "Orange"
    vc1.tabBarItem.image = UIImage(named: "heart")
    
    // Set up the second View Controller
    let vc2 = UIViewController()
    vc2.view.backgroundColor = UIColor.purple
    vc2.tabBarItem.title = "Purple"
    vc2.tabBarItem.image = UIImage(named: "star")
    
    // Set up the Tab Bar Controller to have two tabs
    let tabBarController = UITabBarController()
    tabBarController.viewControllers = [vc1, vc2]
    
    // Make the Tab Bar Controller the root view controller
    window?.rootViewController = tabBarController
    window?.makeKeyAndVisible()

I added TabBarController. It works fine. But my NavigationController doesn't work. I think that is because I set rootViewController for two of them. How should i solve this? Thank you for your time.

like image 272
hummaan Avatar asked Feb 05 '26 19:02

hummaan


1 Answers

You need something like this

let firstVc = UIViewController()
let secondVc = UIViewController()

let firstNav = UINavigationController(rootViewController: firstVc)
let secondNav = UINavigationController(rootViewController: secondVc)

let tabBarController = UITabBarController()
tabBarController.viewControllers = [firstNav, secondNav]

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

of course, fill in your classes and whatnot but the basic idea is this

like image 184
Tomo Norbert Avatar answered Feb 07 '26 17:02

Tomo Norbert