Prevent segue in prepareForSegue method?
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.
Solution 1:
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.
Solution 2:
Note: the accepted answer is the best approach if you can target iOS 6. For targeting iOS 5, this answer will do.
I don't believe it is possible to cancel a segue in prepareForSegue
. I would suggest moving your logic to the point that the performSegue
message is first sent.
If you are using Interface Builder to wire up a segue directly to a control (e.g. linking a segue directly to a UIButton
), then you can accomplish this with a bit of refactoring. Wire the segue to the view controller instead of a specific control (delete the old segue link, and then control-drag from the view controller itself to the destination view controller). Then create an IBAction
in your view controller, and wire the control to the IBAction. Then you can do your logic (check for empty TextField) in the IBAction you just created, and decide there whether or not to performSegueWithIdentifier
programatically.