停止segue并显示警报

时间:2012-02-23 05:16:15

标签: iphone ios ios5 segue uistoryboardsegue

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

3 个答案:

答案 0 :(得分:77)

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

您可以在源视图控制器上简单地实现shouldPerformSegueWithIdentifier:sender:方法。如果要执行segue,请使此方法返回YES;如果不执行,则返回NO

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

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

首先,将segue从按钮的视图控制器设置到目标视图控制器,而不是直接从按钮设置到目标。为segue提供ValidationSucceeded等标识符。

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

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

答案 1 :(得分: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;
}

像魅力一样工作!


使用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
}

答案 2 :(得分:0)

我会举个例子,这是我的代码:

- (IBAction)Authentificate:(id)sender {
if([self WSAuthentification]){
   [self performSegueWithIdentifier:@"authentificationSegue" sender:sender];
}
else
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Authetification Failed" message:@"Please check your Identifications" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
    [alert show];
}

但似乎不起作用,在所有情况下都会执行我的segue。 答案很简单,我们必须从视图控制器连接segue,而不是从Button。