Prevent segue in prepareForSegue method? Prevent segue in prepareForSegue method? ios ios

Prevent segue in prepareForSegue method?


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.


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.


Swift 3:func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool

Return value true if the segue should be performed or false if it should be ignored.

Example:

var badParameters:Bool = trueoverride func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {    if badParameters  {         // your code here, like badParameters  = false, e.t.c         return false    }    return true}