在一个viewcontroller中如何添加一个child viewcontroller

Asked on 04/03/2025

1 search

To add a child view controller in a UIViewController, you can follow these steps:

  1. Instantiate the Child View Controller: Create an instance of the view controller you want to add as a child.

  2. Add the Child View Controller: Use the addChild(_:) method to add the child view controller to the parent.

  3. Add the Child's View to the Parent's View Hierarchy: Add the child view controller's view to the parent's view hierarchy.

  4. Notify the Child View Controller: Call didMove(toParent:) on the child view controller to notify it that it has been added to a parent.

Here's a basic example in code:

let childViewController = YourChildViewController()
addChild(childViewController)
view.addSubview(childViewController.view)
childViewController.didMove(toParent: self)

This process is not directly covered in the provided WWDC session segments, but it is a common practice in UIKit for managing view controller hierarchies. If you are interested in integrating SwiftUI views into a UIKit view controller, you might find the session SwiftUI essentials useful, as it discusses interoperability between SwiftUI and UIKit.