Search code examples
storyboarduitabbarcontrollerios13swift5xcode11

how to present a tabBarViewController(created in storyboard) using code when pressed a particular button in swift5?


I have a viewController called as ViewController and I have a button on it , I want to present a tabBarController (which already contains two viewControllers) when pressed a button and I want it fullscreen I have tried a code

     let tabbar = (self.storyboard?.instantiateViewController(identifier: "TabBar") as? UITabBarController)       
    tabbar!.modalPresentationStyle = .fullScreen
    self.present(tabbar!, animated: true)

the identifier is actually the storyboard id that I have given to the tabBar Controller on storyboard, this code actually works but when I press the button that triggers that code it works fine but when I connect the outlets of the viewControllers present on that tabBar Controller on the next build those Viewcontrollers(those on that taBbar) seems to go black and I am not able to see any components that I designed on storyboard And also I get this message in the console

Attempt to present <Sample_App.TabViewController: 0x7f8f5d847200> on <Sample_App.ViewController: 0x7f8f5c607490> (from <Sample_App.ViewController: 0x7f8f5c607490>) whose view is not in the window hierarchy. please give me a solution and also a bit of explanation here is the snapshot of my story board


Solution

  • You could try put a segue from the ViewController to the TabController

    Set the segue connection

    Now and put an identifier.

    Set the segue ID

    Add a func in your first ViewController and taking the segue identifier to move to the other view.

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "yourSegueID" {
            let tabBarController = segue.destination as! UITabBarController
            tabBarController.title = "TabBarController"
        }
    }
    

    Then add a button action to call this line

    @IBAction func infoMessage(_ sender: UIButton) {
        performSegue(withIdentifier: "yourSegueID", sender: nil)
    }
    

    This is the implementation