【发布时间】:2012-03-13 12:50:20
【问题描述】:
使用 iOS 5 故事板,在一个按钮上我正在执行 segue,我想要对我的文本字段进行验证,如果验证失败,我必须停止 segue 并发出警报。有什么办法吗?
【问题讨论】:
标签: iphone ios ios5 segue uistoryboardsegue
使用 iOS 5 故事板,在一个按钮上我正在执行 segue,我想要对我的文本字段进行验证,如果验证失败,我必须停止 segue 并发出警报。有什么办法吗?
【问题讨论】:
标签: iphone ios ios5 segue uistoryboardsegue
您可以在源视图控制器上简单地实现shouldPerformSegueWithIdentifier:sender: 方法。如果要执行 segue,则使此方法返回 YES,否则返回 NO。
您将需要更改您的 segue 在情节提要中的连接方式并编写更多代码。
首先,设置从按钮的视图控制器到目标视图控制器的 segue,而不是直接从按钮到目标。给 segue 一个标识符,如 ValidationSucceeded。
然后,将按钮连接到其视图控制器上的操作。在操作中,执行验证并根据验证是否成功执行 segue 或显示警报。它看起来像这样:
- (IBAction)performSegueIfValid:(id)sender {
if ([self validationIsSuccessful]) {
[self performSegueWithIdentifier:@"ValidationSucceeded" sender:self];
} else {
[self showAlertForValidationFailure];
}
}
【讨论】:
对我有用并且我认为正确的答案是使用Apple Developer Guide 中的 UIViewController 方法:
shouldPerformSegueWithIdentifier:sender:
我的方法是这样实现的:
- (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;
}
工作就像一个魅力!
为 >= iOS 8 更新了 Swift:
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
}
【讨论】:
我给你举个例子,这是我的代码:
- (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 连接。
【讨论】: