You have - as expected - several options.
Option 1
Use a UIPageViewController. You can then even swipe between the different child view controllers and they will only be loaded when they are needed.
You have to set the UIPageViewController
's dataSource
to an object that implements at least these two methods:
#pragma mark - UIPageViewControllerDataSource
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerBeforeViewController:(UIViewController *)viewController
{
// Return the viewController instance _before_ the given viewController or nil when there are no more view controllers to display.
return nil;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerAfterViewController:(UIViewController *)viewController
{
// Return the viewController instance _after_ the given viewController or nil when there are no more view controllers to display.
return nil;
}
Option 2
Create an outlet for your container view and then programmatically add/remove the child view controller you want to display, like so:
- (void)setCurrentChildViewController:(UIViewController *)viewController
{
// Remove existing child
if (self.currentChildViewController) {
if (self.currentChildViewController.isViewLoaded) {
[self.currentChildViewController.view removeFromSuperview];
}
[self.currentChildViewController willMoveToParentViewController:nil];
[self.currentChildViewController removeFromParentViewController];
}
// Now add viewController as child
[self addChildViewController:viewController];
[viewController didMoveToParentViewController:self];
viewController.view.frame = self.containerView.bounds;
viewController.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self beginAppearanceTransition:YES animated:NO];
[self.containerView addSubview:viewController.view];
[self endAppearanceTransition];
self.currentChildViewController = viewController;
}
Option 3
Hide and show the child view controllers as you have described in your question, but I'd rather pick option 1 or 2, depending on your needs.
Footnote for beginners:
With Storyboards, when you load a UIViewController, you often need to use instantiateViewControllerWithIdentifier:
, so, a simple example
SomeViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"someViewControllerStoryboardID"];
// see method created in option 2
[self setCurrentChildViewController:vc];
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…