ios - 以编程方式嵌入 UIViewController?

标签 ios objective-c iphone uiviewcontroller embed

我有一个带有 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/

相关文章:

ios - 隐藏导航栏上的后退按钮是iOS6

ios - 当 UIViewController 呈现 UIViewControllerAnimatedTransitioning 并在 iOS8 中旋转时,UITabBarController 布局被破坏

iphone - 将 NSImage 转换为 IplImage

ios - FMDatabase 已锁定,类内使用的最佳实践

iphone - 在 iPhone 应用程序中保存数据并下次读取数据的最快方法是什么?

iphone - 如何让 UIView 变得光滑 Shiny ?

iOS - AVCaptureDevice - 自动对焦和相机捕捉曝光

ios - 在 iPhone 上调试 MFI 应用程序

ios - 我想像 Instagram 一样播放视频(如果没有视频则显示图像)?

ios - 具有自定义单元格和标签的heightForRowAtIndexPath