我有一个带有一个容器视图的UIViewController的Storyboard设置,以便我可以在其中嵌入另一个UIViewController.
在某种情况下,我需要更改嵌入式视图控制器.在我的故事板中,我的容器视图不能有两个区段(只有一个嵌入区段).这导致我以编程方式进行.
我的容器视图在我的故事板,没有连接的嵌入.
现在从这一点开始,我如何以编程方式嵌入我所选择的UIViewController对象?
任何帮助非常感谢,谢谢.
解决方法
你可以通过编程来做到这一点,下面是一个方法,它将采用一个bool值来决定哪个视图控制器需要在容器视图中添加,然后将实例化一个对象,之后将它添加到containerView
- (void)addViewControllerToContainerView:(BOOL)addVC1 { // Get storyboard UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"<name of storyboard>" bundle:[NSBundle mainBundle]]; UIViewController *viewController = nil; if (addVC1) { // get viewController with identifier viewController = [storyBoard instantiateViewControllerWithIdentifier:@"<View Controller 1 Identifier>"]; } else { viewController = [storyBoard instantiateViewControllerWithIdentifier:@"<View Controller 2 Identifier>"]; } // lets add it to container view [viewController willMovetoParentViewController:self]; [self.view addSubview:viewController.view]; [self addChildViewController:viewController]; [viewController didMovetoParentViewController:self]; // keep reference of viewController which may be useful when you need to remove it from container view,lets consider you have a property name as containerViewController self.containerViewController = viewController; }
当您需要从容器视图控制器中删除视图控制器时,您可以执行此操作
[self.containerViewController willMovetoParentViewController:nil]; // 1 self.containerViewController.view removeFromSuperView]; [self.containerViewController.view removeFromParentViewController]; self.containerViewController = nil
Apple docs关于集装箱视图控制器