Is it possible for a button to open on a specific tab when using the tab bar controller?

The question is a bit confusing to put it this way, hopefully the image will be a little more useful. Here's the setting:

enter image description here

So, I want the First Look button to open FirstViewController, and I want the Second Look button to open SecondViewController. If I bind the Second View button to SecondViewControlleras follows:

enter image description here

I am losing tab navigation. And if I connect the button to TabViewControlleras follows:

enter image description here

then it will automatically open in FirstViewController. If I'm missing something, it seems like I need to do this with a little extra code, but I can't find anything that explains how to do this.

Thank!

+4
2

Viewcontroller TabBarController . selelctedIndex TabBarController prepareforsegue

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
        }
    }
}
+1

tabViewController .

var index : Int!

@IBAction func button1(_ sender: Any) {
        index = 1
        self.performSegue(withIdentifier: "TabBarSegue", sender: self)
}

@IBAction func button2(_ sender: Any) {
        index = 2
        self.performSegue(withIdentifier: "TabBarSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if(segue.identifier == "TabBarSegue"){
            let videoController : TabBarController = segue.destination as! TabBarController
            videoController.index = index
}

TabBarController .

import UIKit

class TabBarController: UITabBarController {

    var index : Int!


    override func viewDidLoad() {
        super.viewDidLoad()

        selectedIndex = index

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}
0

Source: https://habr.com/ru/post/1672525/


All Articles