Using iOS 5 storyboards, on a button I am performing a segue, what I want is to do validation on my textfield and if validation is failed I have to stop segue and throw an alert. Whats the way to do it?
You can simply implement the shouldPerformSegueWithIdentifier:sender:
method on your source view controller. Make this method return YES
if you want to perform the segue, or NO
if you don't.
You will need to change the way your segue is connected in the storyboard and write a little more code.
First, set up the segue from the button's view controller to the destination view controller, instead of directly from the button to the destination. Give the segue an identifier like ValidationSucceeded
.
Then, connect the button to an action on its view controller. In the action, perform the validation and either perform the segue or show an alert based on whether the validation succeeded. It will look something like this:
- (IBAction)performSegueIfValid:(id)sender {
if ([self validationIsSuccessful]) {
[self performSegueWithIdentifier:@"ValidationSucceeded" sender:self];
} else {
[self showAlertForValidationFailure];
}
}
What worked for me and what I believe to be the correct answer is to use UIViewController method found in Apple Developer Guide:
shouldPerformSegueWithIdentifier:sender:
I implemented my method like so:
- (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;
}
Worked like a charm!
Updated with Swift for >= 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With