Sobes.tech
Junior — Middle

In what scenarios is it appropriate to use UIHostingController in an app?

sobes.tech AI

Answer from AI

UIHostingController is used to integrate SwiftUI into UIKit applications. This is especially useful when you need to:

  • Embed a SwiftUI view into an existing UIKit controller.
  • Gradually migrate an app from UIKit to SwiftUI.
  • Use the advantages of SwiftUI (e.g., declarative UI) without a complete overhaul of the app.

Example of usage:

import SwiftUI
import UIKit

struct MySwiftUIView: View {
    var body: some View {
        Text("Hello from SwiftUI")
    }
}

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

Thus, UIHostingController acts as a bridge between UIKit and SwiftUI.

In what scenarios is it appropriate to use… - sobes.tech