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.
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 theperformSegue
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 anIBAction
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 toperformSegueWithIdentifier
programatically.It's possible in iOS 6 and later: You have to implement the method
In your view controller. You do your validation there, and if it's OK then
return YES;
if it's not thenreturn 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.
Alternatively, it's somewhat bad behavior to offer a button that a user shouldn't press. You can leave the segue wired as stands, but start with the button disabled. Then wire the UITextField's "editingChanged" to an event on the view control ala
The other way is to override method of tableView with willSelectRowAt and return nil if you don't want to show the segue.
showDetails()
- is some bool. In most cases should be implemented in data model being represented in cell withindexPath
.