正如预期的那样,您有几个选择。
选项 1
使用 UIPageViewController。然后,您甚至可以在不同的子视图控制器之间滑动,它们只会在需要时加载。
您必须将UIPageViewController
's设置dataSource
为至少实现以下两种方法的对象:
#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;
}
选项 2
为您的容器视图创建一个插座,然后以编程方式添加/删除您要显示的子视图控制器,如下所示:
- (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;
}
选项 3
隐藏和显示您在问题中描述的子视图控制器,但我宁愿选择选项 1 或 2,具体取决于您的需要。
初学者脚注:
使用 Storyboards,当你加载一个 UIViewController 时,你经常需要使用instantiateViewControllerWithIdentifier:
,所以,一个简单的例子
SomeViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"someViewControllerStoryboardID"];
// see method created in option 2
[self setCurrentChildViewController:vc];