How can you implement tabBarController for View Controllers that are not the InitialViewController?

41 Views Asked by At

So if you want to make the initial view controller a tab bar, you just make a Tab Bar Controller, drag to connect to the view controllers, and set the Tab Bar Controller as the initial view controller.

But say after these tab bars, you currently segue with button press to a view controller called homepage. In SceneDelegate, this homepage is set to rootViewController if the user is logged in, otherwise it is the initial Tab Bar controller.

So, how do you go about making homepage have a Tab Bar with two other View Controllers that are currently being segued from homepage by button presses. You can make a Tab Bar Controller in Storyboard and connect it to the the 3 VC's, but you can't set the Tab Bar Controller as initial view controller

1

There are 1 best solutions below

0
Oleg On

If you need to set a different rootViewController based on your authorization status, simply set rootViewController.

Be sure you don't specify Launch Screen File, otherwise, the code will not work and use your storyboard by default.

enter image description here

Your ViewController in Storyboard must has unique StoryboardID, for example:

enter image description here

And the code will be look like this:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

  var window: UIWindow?

  func isAuthorized() -> Bool {
     // your implementation goes here
     return false
  }

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil)

        if isAuthorized() {
           let vc = storyboard.instantiateViewController(withIdentifier: "myVCID")
           var tabController = UITabBarViewController()           
           tabController.setViewControllers([vc], animated: true)
           window.rootViewController = tabController
        } else {
          let vc = storyboard.instantiateViewController(withIdentifier: "mySecondVCID")
           window.rootViewController = vc
        }

        self.window = window
        window.makeKeyAndVisible()
    }
  }

Here in the code you can initiate any UIViewController from your .storyboard and add it to your UITabBarViewController as a tab.