How to Create a Conditional Segue

2019-08-05 05:01发布

I have created a project in Xcode using storyboards. I created a segue between two of the view controllers with a button using the click and drag method. However, there are a certain set of conditions that I want to be met in order for the segue to happen. So I already coded the button as an IB action and wrote the conditional code in the implementation file. If the conditions are not met, an alert view pops up, and I don't want the segue to happen. But if the conditions are met then I do want the segue to happen.

Is there any way to programmatically command a segue to happen or not happen inside an IB action function? Or any other way to get the same kind of result?

THANKS! Any help is appreciated!

标签: xcode4.3
2条回答
做自己的国王
2楼-- · 2019-08-05 05:56

You can create a custom segue by subclassing UIStoryboardSegue and setting the segue style to "custom" along with your class name in the attributes inspector. Then you can override the perform method in order to see if your conditions are met before you perform the segue. For example

- (void) perform {
    if (...) {
        [[self sourceViewController] presentModalViewController:[self destinationViewController] animated:YES];
    }
}

See also the documentation http://developer.apple.com/library/IOs/#featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomSegues/CreatingCustomSegues.html

Alternatively, you could disable the button as long as your conditions are not met. Maybe that's the better approach, since then the user has a visual indication that the segue won't happen, instead of getting a negative feedback after pressing the button.

查看更多
Explosion°爆炸
3楼-- · 2019-08-05 06:06

I found a great solution for this that someone posted... create a segue that originates from from the status bar of the originating view controller, give it an identifier, and then add this code inside the action button:

[self performSegueWithIdentifier:@"identifierName" sender:sender]; 

Works great!

查看更多
登录 后发表回答