IvOS
IvOS

Reputation: 323

How to know which segue was used using Swift?

I have a main viewController and a detailsViewController. The detailsViewController has 2 buttons. Both buttons are segues back to the main controller but I want to customize the main viewController based on which segue was used. What is the best way to check which segue was used to reach a viewController so that the main viewController can be customized depending on that? - if segue1 leads to the the main viewController then I want label1 hidden. if segue2 leads to the main viewController, then I want label2 hidden.

Upvotes: 7

Views: 4583

Answers (3)

Sridhara Shetty
Sridhara Shetty

Reputation: 107

There is a option for setting Identifier for segue. This should be unique identifier. So that you can identify which segue is activated. Ex:

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "Identifier1" {
        let firstVC = segue.destinationViewController as? FirstViewController

    } else if segue.identifier == "Identifier2" {
        let secondVC = segue.destinationViewController as? SecondViewController

    }
}

Upvotes: 0

imagngames
imagngames

Reputation: 350

In Main View Controller create a variable , something like

var vcOne : Bool = true

Now in DetailsViewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "segue_one"
        {
            let mainVC : MainViewController = segue.destinationViewController as! MainViewController
            secondVC.vcOne = true


        }
        else if segue.identifier == "segue_two"
        {
           let mainVC : MainViewController = segue.destinationViewController as! MainViewController
            secondVC.vcOne = false
        }

    }

Now in MainView Controller

     override func viewWillAppear(animated: Bool) {
             super.viewWillAppear(animated)

             //Now check here for which segue
            if(vcOne)
           {
            // implement for button one click

            }
           else
           {
              // implement for button two click 

           }


        }

Hope it helps you

Upvotes: 11

Fredrik
Fredrik

Reputation: 263

I'd do something like to check which segue was used. You have to set an identifier to the segue in the storyboard though!

    func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "yourIdentifier" {
        let yourVC = segue.destinationViewController as? yourViewController
        //do magic with your destination
    }
}

Upvotes: 1

Related Questions