How to check which segue was used

一曲冷凌霜 提交于 2019-11-30 03:42:12

问题


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.


回答1:


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 = ...
    }
}



回答2:


So firstly you need to set your segues identifier directly in storyborads or through your code using the performSegueWithIdentifier method. Independently the way you choosed, your view controller will fire the following method, so you need to override it to know which segue was sending the message, you do like this:

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


来源:https://stackoverflow.com/questions/16167425/how-to-check-which-segue-was-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!