How to add UIHostingController to an existing UIViewController

In this tutorial you will learn how to add your new SwiftUi UIHostingController view to an existing UIViewController and position it with constraints.

let swiftuiView = YourSwiftUiView()
let controller = UIHostingController(rootView: swiftuiView)
addChild(controller)
controller.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(controller.view)
controller.didMove(toParent: self)
        
            
NSLayoutConstraint.activate([
   controller.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0),
   controller.view.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1.0),
   controller.view.centerXAnchor.constraint(equalTo: view.centerXAnchor),
   controller.view.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])

Other articles