以编程方式将两个视图控制器添加到两个容器视图

Programmatically adding two view controllers to two container views

我有一个包含两个容器的视图控制器。我有每个容器的视图控制器。这三个视图控制器位于不同的故事板中。如何以编程方式将我的两个视图控制器添加到两个容器?

您可以通过

参考不同的故事板
[[UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil] instantiateViewControllerWithIdentifier:@"secondVCSrorybradID"];

并且您应该给 VC 您想要创建的标识符。

而且您可以使用 addSubview 将其添加到任何框架:

首先你需要得到你的故事板。为此,您应该使用 UIStoryboard class

UIStoryboard *firstStoryboard  = [UIStoryboard storyboardWithName: @"FirstStoryboardName"  bundle: nil];
UIStoryboard *secondStoryboard = [UIStoryboard storyboardWithName: @"SecondStoryboardName" bundle: nil];
UIStoryboard *thirdStoryboard  = [UIStoryboard storyboardWithName: @"ThirdStoryboardName"  bundle: nil];

接下来您需要从这些故事板获取初始视图控制器(假设 firstStoryboard 的视图控制器包含这两个容器)

UIViewController *secondVC = (UIViewController *)[secondStoryboard instantiateInitialViewController];
UIViewController *thirdVC  = (UIViewController *)[thirdStoryboard  instantiateInitialViewController];

现在将这两个视图控制器添加到包含容器的视图控制器中的容器中

UIViewController *firstVC = (UIViewController *)[firstStoryboard instantiateInitialViewController];
// TODO: Add secondVC and thirdVC as the children of firstVC 

所以回答你关于将视图控制器添加到容器的问题... 容器视图只是一种使用 segues 在界面构建器中添加子视图控制器的简单方法。

因此,要以编程方式执行此操作,首先从每个相应的情节提要中实例化视图控制器(请参阅 Ch0k018 的回答)。

然后必须将属于容器视图的视图控制器作为子视图控制器添加到主视图控制器。您可以在此处阅读有关遏制的信息 https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html

// Add the child view as subview
childViewController.view.frame = self.containerView.bounds;
[self.containerView addSubview:childViewController.view];
// Need to call these methods to complete  
[self addChildViewController:tableViewController];
[childViewController didMoveToParentViewController:self];

来自 Apple 文档:

Here’s what the code does:

It calls the container’s addChildViewController: method to add the child. Calling the addChildViewController: method also calls the child’s willMoveToParentViewController: method automatically. It accesses the child’s view property to retrieve the view and adds it to its own view hierarchy. The container sets the child’s size and position before adding the view; containers always choose where the child’s content appears. Although this example does this by explicitly setting the frame, you could also use layout constraints to determine the view’s position. It explicitly calls the child’s didMoveToParentViewController: method to signal that the operation is complete.