停止segue并显示警报

Fir*_*ous 39 iphone ios ios5 segue uistoryboardsegue

使用iOS 5故事板,在我执行segue的按钮上,我想要的是在我的文本字段上进行验证,如果验证失败,我必须停止segue并发出警报.这样做的方法是什么?

rob*_*off 77

如果您的部署目标是iOS 6.0或更高版本

您只需shouldPerformSegueWithIdentifier:sender:在源视图控制器上实现该方法即可.YES如果要执行segue,或者NO如果不执行segue,请返回此方法.

如果您的部署目标早于iOS 6.0

您需要在故事板中更改segue的连接方式并编写更多代码.

首先,将segue从按钮的视图控制器设置到目标视图控制器,而不是直接从按钮设置到目标.给segue一个标识符ValidationSucceeded.

然后,将按钮连接到其视图控制器上的操作.在操作中,执行验证并执行segue或根据验证是否成功显示警报.它看起来像这样:

- (IBAction)performSegueIfValid:(id)sender {
    if ([self validationIsSuccessful]) {
        [self performSegueWithIdentifier:@"ValidationSucceeded" sender:self];
    } else {
        [self showAlertForValidationFailure];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它不在文档中,但似乎performSegueWithIdentifier:sender:不调用shouldPerformSegueWithIdentifier:sender:.因此,如果您以编程方式触发segue,则还应以编程方式检查shouldPerformSegueWithIdentifier:sender:之前执行此操作. (3认同)

Sha*_*aun 38

对我有用的以及我认为正确的答案是使用Apple Developer Guide中的 UIViewController方法:

shouldPerformSegueWithIdentifier:发件人:

我这样实现了我的方法:

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    if ([identifier isEqualToString:@"Identifier Of Segue Under Scrutiny"]) {
        // perform your computation to determine whether segue should occur

        BOOL segueShouldOccur = YES|NO; // you determine this
        if (!segueShouldOccur) {
            UIAlertView *notPermitted = [[UIAlertView alloc] 
                                initWithTitle:@"Alert" 
                                message:@"Segue not permitted (better message here)" 
                                delegate:nil 
                                cancelButtonTitle:@"OK" 
                                otherButtonTitles:nil];

            // shows alert to user
            [notPermitted show];

            // prevent segue from occurring 
            return NO;
        }
    }

    // by default perform the segue transition
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

像魅力一样工作!


使用Swift更新为> = iOS 8:

override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
    if identifier == "Identifier Of Segue Under Scrutiny" {
        // perform your computation to determine whether segue should occur

        let segueShouldOccur = true || false // you determine this
        if !segueShouldOccur {
            let notPermitted = UIAlertView(title: "Alert", message: "Segue not permitted (better message here)", delegate: nil, cancelButtonTitle: "OK")

            // shows alert to user
            notPermitted.show()

             // prevent segue from occurring
            return false
        }
    }

    // by default perform the segue transitio
    return true
}
Run Code Online (Sandbox Code Playgroud)

  • shouldPerformSegueWithIdentifier:sender:自iOS 6起可用,不会从iOS 5调用. (4认同)