Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know which segue was used using Swift?

Tags:

swift

segue

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.

like image 308
IvOS Avatar asked Mar 29 '16 06:03

IvOS


2 Answers

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

like image 87
imagngames Avatar answered Oct 21 '22 03:10

imagngames


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
    }
}
like image 42
Fredrik Avatar answered Oct 21 '22 05:10

Fredrik