3

How can we do a push xcode unwind segue programmatically?

I know the simple way is to use the storyboard and pull the button to the 'exit', but what I intend to do is to have some codes run first before the view is exited.

Cœur
  • 37,241
  • 25
  • 195
  • 267
dan
  • 729
  • 2
  • 16
  • 26
  • 1
    Possible duplicate of [How to perform Unwind segue programmatically?](https://stackoverflow.com/questions/12509422/how-to-perform-unwind-segue-programmatically) – Cœur Dec 05 '17 at 14:51

3 Answers3

5

To go back to the rootViewController use:

[self.navigationController popToRootViewControllerAnimated:(BOOL)]

Or to go to a specific controller:

[self.navigationController popToViewController:
    [[self.navigationController viewControllers]
    objectAtIndex:THEINDEXOFTHEVIEWCONTROLLERTOUNWINDTO]
    animated:YES];

For a little more detail, see my answer in this post: Push to root View controller in UIStoryboard

Community
  • 1
  • 1
AlexanderN
  • 2,610
  • 1
  • 26
  • 42
4

If you just want to execute some code before the exit (although keep it simple otherwise you'll get a UI lock until you return something), you could override canPerformUnwindSegueAction:fromViewController:withSender: on your destination controller.

Something like this perhaps:

- (BOOL)canPerformUnwindSegueAction:(SEL)action 
                 fromViewController:(UIViewController *)fromViewController 
                         withSender:(id)sender
{
    // Some operation...

    return YES; // Or NO if something went wrong and you want to abort
}

Otherwise, you could actually create the segue programmatically and manage animation/unwind logic by overriding segueForUnwindingToViewController:fromViewController:identifier:.

You can find the complete documentation here

Alladinian
  • 34,483
  • 6
  • 89
  • 91
1

You can have a segue occur in code by calling this method in UIViewController

- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender

You'll still create the segue in your storyboard between the 2 views, just make sure you name the segue and use the exact name in the identifier parameter

rpledge
  • 61
  • 3
  • Best answer. Simplest while actually using unwind segues! – Fábio Oliveira Jul 24 '14 at 13:33
  • 1
    But then are you not pushing the presenting VC onto the stack, rather than removing the current one and having the previous instance of the presenting VC come to the top of the stack ?? – jesses.co.tt Dec 11 '14 at 17:39