Iurii Ushakov Iurii Ushakov - 1 year ago 101
Swift Question

How to make a segue to second item of tab bar?

I have a strange trouble with making of segue to second item of tab bar from second button. I have

with 2 buttons. First button must be linked with first item of tab bar and second button must be linked with second item of tab bar.

The task looks easy. Making segue for first is elementary (I just linked first button first Tab Bar Controller) but I have a trouble with linking of second button. If I link second button with second View I will see view controller without tab bar. What Do I need to do?

enter image description here
enter image description here

Answer Source

You can use prepare for "segue" to pass to the tabView the next view.

1) Create a CustomTabViewController and load in your tabView. enter image description here

2) select the action from the ViewController to the CustomTabBarViewConstroller. enter image description here

4) Instantiate the buttons in your ViewController and user the sender delegate to select the view to display.

5) Here is the code that you need.

class ViewController: UIViewController {

// Create a value for chosed view
private var nextViewNumber = Int()

override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "tabBar" {

        let nextView = segue.destination as! CustomTabBarViewController

        switch (nextViewNumber) {
        case 1:
            nextView.selectedIndex = 0

        case 2:
            nextView.selectedIndex = 1


@IBAction func FistView(_ sender: UIButton) {
    self.nextViewNumber = 1
    self.performSegue(withIdentifier: "tabBar", sender: self)

@IBAction func SecontView(_ sender: UIButton) {
    self.nextViewNumber = 2
    self.performSegue(withIdentifier: "tabBar", sender: self)



enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download