Xcode storyboard cancel push if a condition is not met Xcode storyboard cancel push if a condition is not met xcode xcode

Xcode storyboard cancel push if a condition is not met


Don't create the segue by dragging from the button to the destination controller. Instead, just drag from the source controller to the destination controller to create a segue. Click on the segue and use the attribute inspector to specify the segue is a push and give the segue an identifier (goToDestination). Then connect the button to an IBAction in the source view controller. In the IBAction method do your checking and if you want to do the push add this line of code:

[self performSegueWithIdentifier: @"goToDestination" sender: self];


The following can also be used and will work for different types of segues like push, unwind, etc. Name the segue from the Storyboard and use the code given here. Return NO for the condition if you do not want the particular segue to be performed and return YES by default. This method should be in the source view controller.

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {    if ([identifier isEqualToString:@"Segue_Name"]) {        NSLog(@"Segue Blocked");        //Put your validation code here and return YES or NO as needed        return NO;    }    return YES;}


If buttonAction is the method that have to execute on button click you have to call two methods inside it1. Method to check the conditions2. Method to control the segue

 - (IBAction)buttonAction:(id)sender     {     [self validateEnteredData];     [self shouldPerformSegueWithIdentifier:kSegueName sender:sender];     }

Your validation method will be looking as follows

-(void)validateEnteredData {if (self.usernameTextField.text.length==0 && self.passwordTextField.text.length==0){    UIAlertView * alert=[[UIAlertView alloc]initWithTitle:kError message:kInvalidationMessage delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];    [alert show];    return;}else if (![self.usernameTextField.text isEqualToString:@"admin"] && ![self.passwordTextField.text isEqualToString:@"pass"]){    UIAlertView * alert=[[UIAlertView alloc]initWithTitle:kError message:kLoginFailed delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];    [alert show];    return;}}

and segue can be controlled by the following code segment

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{if ([identifier isEqualToString:kSegueName]){//Validation: Return NO if you don't want to execute the segue action            if (self.usernameTextField.text.length==0 && self.passwordTextField.text.length==0)    {        return NO;    }    else if (![self.usernameTextField.text isEqualToString:@"admin"] && ![self.passwordTextField.text isEqualToString:@"pass"])    {        return NO;    } }  return YES;}