Question

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?

Was it helpful?

Solution

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];
    }];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top