以编程方式嵌入 UIViewController?

Embed UIViewController Programmatically?

我有一个带有容器视图的 UIViewController 故事板设置,这样我就可以在其中嵌入另一个 UIViewController

在某些情况下,我需要更改嵌入式视图控制器。在我的故事板中,我的容器视图中不能有两个转场(只有一个嵌入转场)。这导致我以编程方式进行。

我的情节提要中有我的容器视图,没有连接的嵌入转场。

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

您可以通过编程方式完成此操作,下面的方法将采用布尔值来决定需要在容器视图中添加哪个视图控制器,然后实例化一个对象,然后将其添加到 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 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 关于容器视图控制器

Swift 带有 UIPageViewController 的版本(我认为这是一个常见的用例)

let pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
// do your PageViewController stuff here (delegate and dataSource)
pageController.willMove(toParent: self)
containerView.addSubview(pageController.view)
pageController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
            pageController.view.topAnchor.constraint(equalTo: containerView.topAnchor),
            pageController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
            pageController.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            pageController.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
])
addChild(pageController)
pageController.didMove(toParent: self)

我不知道如何使用 UIPageViewController 中包含的 UIPageControll,所以我最终使用了自己的实例。但我相信这超出了这个问题的范围。