0Pricing
Swift Academy · Lesson

UIHostingController: SwiftUI Inside UIKit

Embedding SwiftUI views into UIKit apps with UIHostingController.

What is UIHostingController?

UIHostingController is a UIKit view controller that hosts a SwiftUI view hierarchy.

import SwiftUI
let swiftUIView = Text("Hello from SwiftUI")
let hostingVC = UIHostingController(rootView: swiftUIView)

Embedding in a UIViewController

Add a hosting controller as a child view controller using the standard child VC API.

class MyViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    let child = UIHostingController(rootView: ContentView())
    addChild(child)
    view.addSubview(child.view)
    child.view.frame = view.bounds
    child.didMove(toParent: self)
  }
}

All lessons in this course

  1. UIViewRepresentable: Wrapping UIKit Views
  2. Coordinator Pattern for Delegate Communication
  3. UIViewControllerRepresentable
  4. UIHostingController: SwiftUI Inside UIKit
← Back to Swift Academy