How to check which segment was used

I got two segments that lead to the same viewController . There are 2 buttons that are connected to the same viewController using 2 segments. In this 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 that the prepareForSegue method prepareForSegue , but I cannot use it for my purpose, because I need to put prepareForSegue in the class where the 2 buttons are located, and I do not want it there, but I want it to be in viewControllers , because that i need to access and set some variables in this class.

+8
ios objective-c iphone uistoryboardsegue
source share
2 answers

You need to set the variable of the second viewcontroller in the prepareforsegue method of the first. Here's how to do it:

 - (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 this property in the second vc to understand how you got there. If you created 2 segues in a storyboard for 2 buttons, then only the segue identifier is enough to set the corresponding property value. Then the 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 = ... } } 
+8
source share

So, first you need to set your segues identifier directly in storyborads or through your code using the performSegueWithIdentifier method. No matter how you choose, the controller of your view will run the following method, so you need to redefine it to find out which segue sending the message, you do this:

  -(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"ButtonSegueIdentifierOne"]) { // button 1 } if ([segue.identifier isEqualToString:@"ButtonSegueIdentifierTwo"]) { // button 2 } } 
+2
source share

All Articles