How it works
A UIHostingController is a UIViewController subclass that hosts a SwiftUI view hierarchy inside a UIKit interface. It acts as the bridge between the two frameworks: you hand it a SwiftUI view as its root content, and it manages a backing view that participates in UIKit's view-controller machinery — view lifecycle, layout, and navigation. Reach for it whenever you need to drop SwiftUI into an app that's still driven by UIKit, such as pushing a SwiftUI screen onto a UINavigationController or embedding one as a child view controller.
Wrap a SwiftUI view with init(rootView:)
The primary initializer takes any value conforming to
Viewand stores it as the controller's content. Here you pass an instance of theUIHostingControllerDemoview, and the hosting controller renders itsbody— theVStackofImageandText— as the controller's view.Read and replace content through the rootView property
The hosted view is exposed as the
rootViewproperty, which you can both read and assign after creation. ReassigningrootViewswaps the displayed SwiftUI content in place, so the sameUIHostingControllercan show a differentUIHostingControllerDemoconfiguration without creating a new controller.Present it like any UIViewController
Because
UIHostingControlleris aUIViewController, you use it through standard UIKit APIs —present(_:animated:),pushViewController(_:animated:), or adding it as a child controller. The SwiftUI content, including the.padding()applied to theVStack, lays out within the controller's managedview.Let the hosted view drive sizing
The hosting controller measures the intrinsic size of its SwiftUI content and exposes it to UIKit's layout system through the view's
intrinsicContentSizeand Auto Layout. The.font(.headline)and.multilineTextAlignment(.center)modifiers on theTextviews shape that measured content, which the controller then fits into its UIKit container.
rootView's Text("Hosted SwiftUI") to a longer string and observe how the UIHostingController resizes its managed view to fit the new SwiftUI content.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct UIHostingControllerDemo: View {
var body: some View {
VStack(spacing: 12) {
Image(systemName: "swift")
.font(.largeTitle)
.foregroundStyle(.orange)
Text("Hosted SwiftUI")
.font(.headline)
Text("This view is the rootView of a UIHostingController, bridging SwiftUI into a UIKit hierarchy.")
.font(.caption)
.multilineTextAlignment(.center)
.foregroundStyle(.secondary)
}
.padding()
}
}