addChildViewController method is only for adding child viewControllers to containerViewController?

时间:2018-03-25 20:59:57

标签: ios cocoa-touch uiviewcontroller

I see the description of this method in Apple says

func addChildViewController(_ childController: UIViewController)

This method is only intended to be called by an implementation of a custom container view controller. If you override this method, you must call super in your implementation.

I see, so many examples that people use addChildViewController everywhere without containerViewController.

For example: I did not use containerView. I added like in the below? İt is correct?

   // Create child VC
     let childVC = UIViewController()

    // Set child VC
    self.addChildViewController(childVC)

    // Add child VC's view to parent
    self.view.addSubview(childVC.view)

    // Register child VC
    childVC.didMove(toParentViewController: self)

    // Setup constraints for layout
    childVC.view.translatesAutoresizingMaskIntoConstraints = false
    childVC.view.topAnchor.constraint(equalTo: heroView.bottomAnchor).isActive = true
    childVC.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    childVC.view.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
    childVC.view.heightAnchor.constraint(equalToConstant: height).isActive = true

1 个答案:

答案 0 :(得分:2)

Like the documentation says, that method is intended to be used by view controllers that can contain another view controller. An example would be the navigation and tab bar controllers.

If you implemented a custom controller that, for example, put one controller on the top half on the screen and one on the bottom half, when you set the bottomHalfViewController property, you would call the addChildViewController method to let your controller know that it should handle that view controller as it's child.

This means that it will forward all view lifecycle calls like viewWillAppear: