Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cancel a segue that is connected to an UIButton

I'm working on this tutorial, which shows how to create an app with storyboards. My viewController has two UIButtons and I have connected a segue to those UIButtons. These segues push a new viewController.

Now I am looking for a way to cancel this segue if a certain condition becomes true. When I used the old xib files to create my interface I was able to do something like this:

-(IBAction)sendButton:(id)sender {
  if(TRUE) {
    // STOP !!  
  }
}

This does not work anymore. How can I cancel the push of the new viewController?

like image 848
Qooe Avatar asked Mar 23 '12 09:03

Qooe


2 Answers

Nope. You can't cancel segues that are directly linked to interface elements like your UIButton.

But there is a workaround.

  1. Remove the segue that is linked to the button
  2. Add a segue from the viewController (the one with the button) to the viewController that should be pushed. This must be a segue that is not connected to a interface element. To do this you can start the segue from the status bar. Or create the segue in the left sidebar.
  3. Select this segue, open the attributes inspector and change the Identifier of the segue (e.g. PushRedViewController)
  4. Select Xcodes assistant view, so you can see the .h file of the viewController with the button.
  5. Connect the button to an action. To do this select the button and control-drag to the .h file. Select action in the menu and name your action (e.g. redButtonPressed:)
  6. Open the implementation of your viewController
  7. change the action from step 5 to something like this:

    - (IBAction)redButtonPressed:(id)sender {
        [self performSegueWithIdentifier:@"PushRedViewController" sender:sender];
    }
    
like image 171
Matthias Bauch Avatar answered Nov 07 '22 17:11

Matthias Bauch


You can actually do this by adding following method into your code

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender   {

if([identifier isEqualToString:@"btnSegue"])
{

   return YES;
}
else{
    return NO;
}

}

Lets assume your segue is btnSegue.And if you need the segue to be performed based on some condition you can have following code

if(check)
{
 [self performSegueWithIdentifier:@"btnSegue" sender:self];
}

Where check is BOOL which you can set true or false based on your condition.

like image 38
Aadil Keshwani Avatar answered Nov 07 '22 15:11

Aadil Keshwani