Prevent segue in prepareForSegue method?

Shmidt picture Shmidt · Nov 9, 2011 · Viewed 94.9k times · Source

Is it possible to cancel a segue in the prepareForSegue: method?

I want to perform some check before the segue, and if the condition is not true (in this case, if some UITextField is empty), display an error message instead of performing the segue.

Answer

Abraham picture Abraham · Oct 10, 2012

It's possible in iOS 6 and later: You have to implement the method

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

In your view controller. You do your validation there, and if it's OK then return YES; if it's not then return NO; and the prepareForSegue is not called.

Note that this method doesn't get called automatically when triggering segues programmatically. If you need to perform the check, then you have to call shouldPerformSegueWithIdentifier to determine whether to perform segue.