gpt4 book ai didi

ios - 以编程方式嵌入 UIViewController?

转载 作者:IT王子 更新时间:2023-10-29 07:52:49 27 4
gpt4 key购买 nike

我有一个带有 UIViewController 和容器 View 的 Storyboard 设置,这样我就可以在其中嵌入另一个 UIViewController

在某些情况下,我需要更改嵌入式 View Controller 。在我的 Storyboard中,我的容器 View 中不能有两个转场(只有一个嵌入转场)。这让我以编程方式进行。

我的 Storyboard中有我的容器 View ,没有连接的嵌入转场。

现在,我该如何以编程方式嵌入我选择的 UIViewController 对象?

最佳答案

您可以通过编程方式执行此操作,下面是一个方法,该方法将采用 bool 值来决定需要在容器 View 中添加哪个 View Controller ,然后实例化一个对象,然后将其添加到 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;
}

当你需要从容器 View Controller 中移除 View Controller 时,你可以这样做

   [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 docs关于容器 View Controller

关于ios - 以编程方式嵌入 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32166319/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com