0

I need to embed a SwiftUI View into a UIViewController's view.
Do I need to write addChild(hostingController) and hostingController.didMove(toParent: self) at the end of viewDidLoad()?

class EmbedSwiftUIViewViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let swiftUIView = SwiftUIView()
        let hostingController = UIHostingController(rootView: swiftUIView)
        view.addSubview(hostingController.view)

        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
        ])

        // Do I need to write this two lines?
        // addChild(hostingController)
        // hostingController.didMove(toParent: self)
    }
}

struct SwiftUIView: View {
    var body: some View {
        ZStack {
            Color.blue
            Text("SwiftUI View")
        }
    }
}

If I write it, the swipe gesture to back is disabled, but if I don't write it, the swipe gesture works fine.
This may be a problem specific to my project environment, but I would like to know if there is any problem without writing addChild() and didMove(toParent:) anyway.

Mac
  • 137
  • 1
  • 8
  • [Related](https://stackoverflow.com/questions/67114401/does-uihostingcontroller-have-to-be-in-the-view-controller-hierarchy). – Sweeper Jul 27 '23 at 07:51
  • Apple's defined order is: `addChild(...)` / `addSubview(child's view)` / `child.didMove(...)`. It is not *strictly* necessary to add a controller as a child just to get its view, but if you use Debug View Hierarchy you will see a difference. Not sure what you mean by *"swipe gesture to back is disabled"*? If I use a `UINavigationController` and push to your `EmbedSwiftUIViewViewController`, I can swipe back (both with and without the addChild). – DonMag Jul 28 '23 at 17:21

0 Answers0