Best practice to transition between view controllers in a custom container view controller in a storyboard?

2.3k views Asked by At

I have a setup that is very similar to a UITabBarController but for various reasons I need to create my own custom container root controller.

I would like to create a custom transition between my two view controllers as specified in the picture (VC 1 & VC 2).

Storyboard Setup

Is it correct to add my two view controllers as children to my master controller and do a view animation on the container views that live within the root view controller? That would mean that both of my view controllers are instantiated at once.

Or do I go about doing something like having VC 1 live as a child view controller on my root view controller while later instantiating VC 2 in my code when the transition takes place. This of course would mean that I would have VC 2 live in my storyboard but not connected to the root view controller and be instantiated through the Storyboard ID. And I would obviously be using the custom transition protocols that we received in iOS 7.

Or is there some other option?

1

There are 1 answers

4
mbo42 On

Since they're both contained within one ViewController, you probably won't transition between them using present and dismiss.

I recently had a similar scenario where I finally went with using my own custom transitions from the ContainerViewController.

There are some things to think about when using ViewController containment. You should checkout this link on developer.apple, containing some good practices and examples on View Controller containment and how to animate in between ChildViewControllers.

When it comes to allocation, I'd say it's up to you. Unless these ViewControllers take a lot of memory, I'd probably go with instantiating the first one to be shown, and doing a lazy initialisation (initialise when needed) on the second one, and then retain them both in memory. After a transition has been made, make sure to remove the "unused" ViewController's view from the container and it should be all good.

Here's a simple example to fade from the firstVC's view to the secondVC's view:

[self addChildViewController:self.secondViewController];
[self.view insertSubview:self.secondViewController.view belowSubview:self.firstViewController.view];

[UIView animateWithDuration:0.4 animations:^{
    self.firstViewController.view.alpha = 0;
} completion:^(BOOL finished) {
    [self.firstViewController willMoveToParentViewController:nil];
    [self.firstViewController.view removeFromSuperview];
    [self.firstViewController removeFromParentViewController];
    [self.secondViewController didMoveToParentViewController:self];
}];