使用 iOS 5 故事板,在一个按钮上我正在执行 segue,我想要对我的文本字段进行验证,如果验证失败,我必须停止 segue 并发出警报。有什么办法吗?
问问题
29959 次
3 回答
77
如果您的部署目标是 iOS 6.0 或更高版本
您可以简单地shouldPerformSegueWithIdentifier:sender:
在源视图控制器上实现该方法。YES
如果您想执行 segue,或者NO
不这样做,请让此方法返回。
如果您的部署目标早于 iOS 6.0
您将需要更改您的 segue 在情节提要中的连接方式并编写更多代码。
首先,设置从按钮的视图控制器到目标视图控制器的 segue,而不是直接从按钮到目标。给 segue 一个标识符,如ValidationSucceeded
.
然后,将按钮连接到其视图控制器上的操作。在操作中,执行验证并根据验证是否成功执行 segue 或显示警报。它看起来像这样:
- (IBAction)performSegueIfValid:(id)sender {
if ([self validationIsSuccessful]) {
[self performSegueWithIdentifier:@"ValidationSucceeded" sender:self];
} else {
[self showAlertForValidationFailure];
}
}
于 2012-02-23T06:09:57.523 回答
38
对我有用并且我认为正确的答案是使用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;
}
像魅力一样工作!
使用 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
}
于 2012-09-28T06:27:36.837 回答
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 连接。
于 2013-06-20T14:53:41.220 回答