以编程方式嵌入 UIViewController? [英] Embed UIViewController Programmatically?
问题描述
我有一个带有 UIViewController
和容器视图的 Storyboard 设置,以便我可以在其中嵌入另一个 UIViewController
.
I have a Storyboard setup with a UIViewController
with an container view so that I can embed another UIViewController
inside of it.
在某些情况下,我需要更改嵌入式视图控制器.在我的故事板中,我的容器视图中不能有两个 segue(只有一个嵌入 segue).这导致我以编程方式进行操作.
In a certain scenario I need to change the embedded view controller. In my storyboard I cannot have two segues from my container view (only a single embed segue). Which leads me to doing it programatically.
我的故事板中有我的容器视图,没有连接的嵌入转场.
I have my container view in my storyboard with no connected embed segue.
现在,如何以编程方式嵌入我选择的 UIViewController
对象?
Now from this point, how can I programmatically embed my chosen UIViewController
object?
推荐答案
你可以通过编程来做到这一点,下面是一个方法,它会使用一个 bool 值来决定需要在容器视图中添加哪个视图控制器,然后将实例化一个对象,然后将其添加到 containerView
You can do this by programmatically, below is the method which will take a bool value to make decision which view controller need to be added in container view and then will instantiate an object and after that will add it to 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;
}
当您需要从容器视图控制器中删除视图控制器时,您可以这样做
When you need remove view controller from container view controller you can do this
[self.containerViewController willMoveToParentViewController:nil]; // 1
self.containerViewController.view removeFromSuperView];
[self.containerViewController removeFromParentViewController];//this line is updated as view is removed from parent view cotnroller istead of its viewcontroller is removed from parentViewController
self.containerViewController = nil
Apple 文档关于容器视图控制器
这篇关于以编程方式嵌入 UIViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!