0

I have a few ViewControllers that all have buttons which should segue to some others. There will never be a back button, but instead everything is connected through a bunch of loops so that there is never a dead end. So I'd like to fully transition from one View Controller to another, and have the old View Controller be completely deleted. There is no hierarchy and no parent/child relationship between the View Controllers. How should I handle this situation?

user1778856
  • 641
  • 4
  • 10
  • 17

1 Answers1

1

Instantiate the view controller you want to go to, then set it as the window's root view controller.

NextViewController *next = [self.storyboard instantiateViewControllerWithIdentifier:@"Next"]; // or other instantiation method depending on how you create your controller
self.view.window.rootViewController = next;

You could do this with custom segues if you want to show the flow from controller to controller in your storyboard (you wouldn't need any code at all then). The custom segue's perform method would look like this,

@implementation RootVCReplaceSegue

-(void)perform {
    UIViewController *source = (UIViewController *)self.sourceViewController;
    source.view.window.rootViewController = self.destinationViewController;
}

If you want a fade animation, you can add a snapshot of the source view controller as a subview of the destination view controller's view, then fade it out,

-(void)perform {
    UIViewController *source = (UIViewController *)self.sourceViewController;
    UIView *sourceView = [source.view snapshotViewAfterScreenUpdates:YES];
    [[self.destinationViewController view] addSubview:sourceView];
    source.view.window.rootViewController = self.destinationViewController;
    [UIView animateWithDuration:.5 animations:^{
        sourceView.alpha = 0;
    } completion:^(BOOL finished) {
        [sourceView removeFromSuperview];
    }];
}
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Will there be anyway to handle this through the storyboard so I don't have a bunch of floating controllers that are connected programmatically? – user1778856 Apr 29 '14 at 05:53
  • @user1778856, sorry, I don't know what you mean by that. If you create your controllers in the storyboard, they will be "floating" in the sense that they won't have any segues connecting them. There's no problem with that, as long as you give each controller an identifier so you can instantiate it. If you want to show the flow from one controller to the next, you could connect them with custom segues. You would then have to write a custom perform method in the segue class to do what I said in my answer. – rdelmar Apr 29 '14 at 05:58
  • Thanks! This works, however, how would I be able to add a fade out, fade in animation to this? – user1778856 Apr 29 '14 at 06:13
  • @user1778856, yeah, that's easy, I've updated my answer with that code. – rdelmar Apr 29 '14 at 15:36