0

I have a UITabBarController which has 4 tabs. I want to show different view controllers for second tab bar item. Depending on the condition I want to show the view controllers for that tab bar item.

I wrote following code :

UITabbarController -

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        if item.tag == 2 {
            if UserDefaults.standard.bool(forKey: "FirstTimeUser") == true {
                //                let vc1 = storyboard?.instantiateViewController(identifier: "CreateNewProjectViewController") as! CreateNewProjectViewController
                //                self.navigationController?.pushViewController(vc1, animated: true)
                
                let vc1 = self.storyboard?.instantiateViewController(withIdentifier: "CreateNewProjectViewController") as! CreateNewProjectViewController
                let window = UIApplication.shared.windows.first
                window?.rootViewController = vc1
                tabBarController?.tabBar.isHidden = false
            }else {
                //                let vc2 = storyboard?.instantiateViewController(identifier: "ProjectsViewController") as! ProjectsViewController
                //                self.navigationController?.pushViewController(vc2, animated: true)
                let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "ProjectsViewController") as! ProjectsViewController
                let window = UIApplication.shared.windows.first
                window?.rootViewController = vc2
                tabBarController?.tabBar.isHidden = false
            }
        }
    }

I tried with navigationController but it is showing blank screen.

If I try setting the view controller with "

let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "ProjectsViewController") as! ProjectsViewController
                    let window = UIApplication.shared.windows.first
                    window?.rootViewController = vc2
                    tabBarController?.tabBar.isHidden = false

". It does not show the tab bar, please help me get it correctly. Thank you!

3
  • Where does a guy named storyboard? come from? Why don't you safely unwrap optional variables?
    – El Tomato
    Commented Jul 1, 2021 at 6:33
  • once the code window?.rootViewController = vc1 runs, where is your UITabBarController? Commented Jul 1, 2021 at 7:49
  • Your tabbar controller can be configured during setup process based on the "FirstTime" user check. Why trying to updated at didSelect ?
    – RTXGamer
    Commented Jul 1, 2021 at 8:36

0