How to check which segue was used

nonuma picture nonuma · Apr 23, 2013 · Viewed 7.1k times · Source

I got two segue's which lead to the same viewController. There are 2 buttons which are connected to the same viewController using 2 segues. In that viewController I need to check which button was clicked. So actually I need to check which segue was used/preformed. How can I check this in the viewControllers class? I know there is the prepareForSegue method, but I cannot use this for my purpose because I need to put the prepareForSegue in the class where the 2 buttons are, and I don't want it there but I want it in the viewControllers class because I need to access and set some variables in that class.

Answer

guenis picture guenis · Apr 23, 2013

You need to set a variable of the second viewcontroller in the prepareforsegue method of first one. This is how it is done:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:segueIdentifier1])
    {
        SecondViewController *secondVC = (SecondViewController *)segue.destinationViewController;
        if(sender.tag == ...) // You can of course use something other than tag to identify the button
        {
            secondVC.identifyingProperty = ...
        }
        else if(sender.tag == ...)
        {
            secondVC.identifyingProperty = ...
        }
    }
}

Then you can check that property in the second vc to understand how you came there. If you have created 2 segues in the storyboard for 2 buttons, then only segue identifier is enough to set the corresponding property value. Then code turns into this:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:segueIdentifier1])
    {
        SecondViewController *secondVC = (SecondViewController *)segue.destinationViewController;
        secondVC.identifyingProperty = ...
    }
    else if([segue.identifier isEqualToString:segueIdentifier2])
    {
        SecondViewController *secondVC = (SecondViewController *)segue.destinationViewController;
        secondVC.identifyingProperty = ...
    }
}