In a UIKit app, how do you show a new SwiftUI checkout screen inside an existing UINavigationController, and how does data reach it?
answer
- a view controller that owns SwiftUI
- init(rootView:)
- push it like any controller
- closures carry events back
- new tree, new environment
basics
~20 sWrap the SwiftUI view in a UIHostingController(rootView:) and push that controller like any other. Data goes in through the root view's initializer or the rootView property, and events come back through closures or a shared model.
solid answer
~40 sSwiftUI views are not view controllers, so UIKit needs an adapter: `UIHostingController`, a `UIViewController` subclass that owns a SwiftUI hierarchy. You build the screen with its inputs, `UIHostingController(rootView: CheckoutView(total: cart.total, onPlaceOrder: { ... }))`, set its `title` and call `pushViewController(_:animated:)`; it can also be presented or embedded as a child view controller. Data flows in through the root view's initializer, and you can swap the whole view later by assigning `rootView`. Results flow out through closures you pass in, or through a shared observable model both sides hold. One thing does not travel: the hosted screen starts its own SwiftUI hierarchy, so environment values your other SwiftUI screens set are not there unless you add them to the root view.
code
swift · 27 linesimport SwiftUI
import UIKit
struct CheckoutView: View {
let total: Decimal
let onPlaceOrder: () -> Void
var body: some View {
VStack(spacing: 16) {
Text(total, format: .currency(code: "EUR"))
Button("Place order", action: onPlaceOrder)
}
}
}
final class CartViewController: UIViewController {
var cartTotal: Decimal = 42
func showCheckout() {
let checkout = CheckoutView(total: cartTotal) { [weak self] in
self?.navigationController?.popToRootViewController(animated: true)
}
let host = UIHostingController(rootView: checkout)
host.title = "Checkout"
navigationController?.pushViewController(host, animated: true)
}
}go deeper
Recall the type and its initializer: UIHostingController(rootView:) is a view controller, so you push, present or embed it exactly like one.
Explain the two data directions: inputs through the root view or rootView assignment, outputs through closures or a shared observable model.
Point out what the boundary drops, chiefly environment values set by other SwiftUI ancestors, and show how child containment keeps appearance and trait callbacks correct.
Treat the hosting controller as the contract between a UIKit flow and a SwiftUI screen: decide which dependencies every hosted screen receives and where that wiring lives.
## Why UIKit needs an adapter A UIKit app is built from **view controllers**: `UINavigationController` pushes them, `present(_:animated:completion:)` shows them modally, and container controllers embed them as children. A SwiftUI screen is something else entirely, a `View` value that describes an interface and that SwiftUI renders and keeps up to date. UIKit has no idea how to push a `View`. The adapter is **`UIHostingController`**, available since iOS 13. Apple's documentation describes it as "a UIKit view controller that manages a SwiftUI view hierarchy". It is an ordinary `UIViewController` subclass, generic over the SwiftUI view it shows, so anything UIKit can do with a view controller it can do with a hosting controller: - **push** it with `pushViewController(_:animated:)`; - **present** it modally; - **embed** it as a child view controller inside a UIKit screen. The opposite direction, putting a UIKit view inside a SwiftUI screen, uses the representable protocols (`UIViewRepresentable`, `UIViewControllerRepresentable`). Mixing the two up is a common junior slip: a SwiftUI screen entering a UIKit app goes through a hosting controller (SwiftUI rows inside UIKit cells use `UIHostingConfiguration` instead). ## Pushing the checkout screen Suppose a long-lived UIKit shopping app wants a new checkout screen written in SwiftUI, shown from the existing cart screen inside the app's `UINavigationController`. 1. **Build the SwiftUI view with its inputs.** `CheckoutView(total: cartTotal, onPlaceOrder: { ... })`. The view's initializer is its API: it takes the data it shows and the callbacks it fires. 2. **Wrap it.** `let host = UIHostingController(rootView: checkout)`. The `rootView:` label is the one the initializer declares. 3. **Configure it as a view controller.** For example `host.title = "Checkout"`, which the navigation bar shows like any pushed controller's title. 4. **Push it.** `navigationController?.pushViewController(host, animated: true)`. From UIKit's point of view nothing else changes: the back button, the swipe-to-go-back gesture and the navigation bar behave as they do for every other screen, because the navigation controller is still the one managing the stack. ## How data crosses the boundary | Direction | Mechanism | When to use it | |---|---|---| | UIKit to SwiftUI, once | Root view initializer arguments | Data known when the screen opens, such as the cart total | | UIKit to SwiftUI, later | Assign a new value to `host.rootView` | You hold the controller and want to rebuild the root view with new inputs | | UIKit to SwiftUI, live | An observable model object both sides hold | Data that keeps changing while the screen is visible | | SwiftUI to UIKit | Closures passed in the initializer | Events: order placed, cancelled, address chosen | A few rules keep this clean: - **Prefer typed closures** for events. A closure such as `onPlaceOrder` makes the screen's outputs part of its signature and is easy to test. - **Capture the UIKit side weakly** in those closures (`[weak self]`), because the hosting controller keeps its root view, and the root view keeps the closure. - **Use a shared model for live data.** If the SwiftUI view reads properties of an `@Observable` class (iOS 17) or an `ObservableObject`, SwiftUI re-renders the parts that read a changed property; UIKit code only mutates the model. - **`rootView` is settable.** Assigning it replaces the root view value; SwiftUI then updates the hosted hierarchy to match the new value. ## What the hosted screen does not inherit A hosting controller **starts a new SwiftUI hierarchy**. SwiftUI's environment flows from ancestor views to descendants inside one hierarchy, and the cart screen is a UIKit view controller, not a SwiftUI ancestor. So: - Objects or values that other SwiftUI screens install with `environment(_:)`, `environment(_:_:)` or `environmentObject(_:)` are **not** present in the new hierarchy. Apple's documentation for `Environment` says that when a view reads an object by type and it is not in the environment, **SwiftUI throws an exception**, so the app crashes. Attach what the screen needs to its root view: `UIHostingController(rootView: CheckoutView(...).environment(cart))`. - Values SwiftUI derives from UIKit's **trait collection**, such as color scheme, Dynamic Type size, layout direction and size classes, do reach hosted content, because the hosting controller sits in UIKit's trait hierarchy. ## Embedding instead of pushing When the SwiftUI view is only part of a UIKit screen, embed the hosting controller as a **child view controller**: call `addChild(host)`, add `host.view` to your view hierarchy with constraints, then call `host.didMove(toParent: self)`. Containment keeps the controller in UIKit's view controller hierarchy, so it receives appearance callbacks and has a place to present from. How the embedded view reports its size to Auto Layout is a separate concern handled by the hosting controller's sizing options. ## What interviewers listen for - The type name and initializer: `UIHostingController(rootView:)`. - That it is pushed, presented or embedded like any view controller. - A clear answer for both data directions, with closures for events. - Awareness that the hosted screen gets a fresh environment and needs its dependencies attached.
- The checkout screen reads a cart model with @Environment(Cart.self) and crashes when pushed from UIKit; why?A `UIHostingController` starts a new SwiftUI hierarchy, so objects other SwiftUI screens installed with `environment(_:)` are not in it. Reading a non-optional object by type that is missing makes SwiftUI raise an exception. Attach the object to the root view, `UIHostingController(rootView: CheckoutView().environment(cart))`, or read it as optional and handle `nil`.
- How would you place the same SwiftUI view as one section of an existing UIKit screen instead of a whole pushed screen?Embed the hosting controller as a child: `addChild(host)`, add `host.view` to your hierarchy with constraints or to a stack view, then call `host.didMove(toParent: self)`. Containment puts the controller in UIKit's view controller hierarchy, so it receives appearance callbacks and has a place to present from; adding only `host.view` leaves the controller detached.
- When the cart total changes while checkout is on screen, how does the hosted view see it?Either assign a new value to `host.rootView`, rebuilding the root view with the new total, or pass an observable model, an `@Observable` class from iOS 17 or an `ObservableObject` before that, which the SwiftUI view reads; SwiftUI then re-renders the parts that read the changed property without any UIKit code.
- Pushing the SwiftUI view itself onto the navigation controller without a hosting controller.
- Using UIViewRepresentable to put a SwiftUI screen into a UIKit app.
- Expecting environment objects from other SwiftUI screens to appear inside a new hosting controller.
- Adding the hosting controller's view as a subview without addChild and didMove(toParent:).
- Capturing the presenting view controller strongly in the hosted view's callback closures.