Search code examples
iosswiftswift3uitabbarcontrolleruistoryboardsegue

Is it possible for a button to open into a specific tab when using the Tab Bar Controller?


The question is a little confusing to articulate so hopefully an image will be a little more helpful. Here's the setup:

enter image description here

So, I want the First View button to open the FirstViewController, and I want the Second View button to open the SecondViewController. If I link the Second View button to the SecondViewController like this:

enter image description here

I lose the tab navigation. And if I connect the button to the TabViewController like this:

enter image description here

then it will automatically open into the FirstViewController. Unless I'm missing something, it seems like this would need to be done with a little extra code but I cannot seem to find anything that explains how to do this.

Thank you!


Solution

  • Create storyboard segue from Viewcontroller to TabBarController with an identifier. Then assign selelctedIndex value of TabBarController in prepareforsegue method

    storyboard

    @IBAction func firstBtnAction(_ sender: Any) {
        (sender as! UIButton).tag = 0
        performSegue(withIdentifier: "tabBar", sender: sender)
    }
    @IBAction func secBtnAction(_ sender: Any) {
        (sender as! UIButton).tag = 1
        performSegue(withIdentifier: "tabBar", sender: sender)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "tabBar" {
            if let vc = segue.destination as? UITabBarController {
                vc.selectedIndex = (sender as! UIButton).tag
            }
        }
    }