Search code examples
iosswiftuitabbarcontrollerswift5xcode11

Displaying View Controller within a UITabBarController programatically in Swift 5


In my app when the user logs in, they should be taken to a welcome screen, which is part of a TabBarController. But for some reason, when I run the following lines, the welcome screen (HomeScreenViewController) shows up without the TabBar navigation buttons at the bottom.

let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeScreenViewController
self.view.window?.rootViewController = homeViewController
self.view.window?.makeKeyAndVisible()

Inspired by another StackOverflow post, I tried this, but it didn't work either:

let homeController = self.storyboard?.instantiateViewController(identifier:Constants.Storyboard.homeViewController)
(TabBarController.currentInstance?.selectedViewController as?UINavigationController)?.pushViewController(homeController!, animated: true)

For reference, the name of my UITabBarController class is TabBarController and the identifier can be accessed via

Constants.Storyboard.tabBarCont

Thanks!


Solution

  • I think you can try this..

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
                // Override point for customization after application launch.
            window = UIWindow(frame: UIScreen.main.bounds)
    
            let tabBarController = UITabBarController()
    
    let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeScreenViewController
    let anyOtherViewController = self.storyboard?.instantiateViewController(identifier: anyOtherViewController) as? AnyOtherViewController
    
            homeViewController.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "home_image"),tag: 1)
            anyOtherViewController.tabBarItem = UITabBarItem(title: "Other",image:UIImage(named: "other") ,tag:2)
            tabBarController.viewControllers = [homeViewController, anyOtherViewController] 
    
            window?.rootViewController = tabBarController
            window?.makeKeyAndVisible()
            return true
         }