UIHostingController 是 Apple 在 SwiftUI 与 UIKit 混合开发中提供的桥梁组件,它的作用是在 UIKit 中嵌入 SwiftUI 视图。
基本定义
class UIHostingController<Content> : UIViewController where Content : View
UIHostingController 是一个继承自 UIViewController 的类。
它可以包装任何 SwiftUI 的 View,让这个 SwiftUI 界面能够被当作 UIKit 的界面来使用。
使用场景
主要是在以下几种情况:
1、在 UIKit 项目中使用 SwiftUI 界面
比如已有 UIKit 应用(使用 UIViewController,UINavigationController 等),但想用 SwiftUI 开发某个页面或模块。
2、作为 SwiftUI View 的容器
将 SwiftUI 的 View 包装为 UIViewController 后,可以像普通控制器一样 push、present、embed。
示例代码
1、从 UIKit 中 present 一个 SwiftUI 视图
import SwiftUI
struct MySwiftUIView: View {
var body: some View {
Text("这是 SwiftUI 页面")
}
}
// UIKit 的 ViewController 中使用:
let swiftUIView = MySwiftUIView()
let hostingController = UIHostingController(rootView: swiftUIView)
present(hostingController, animated: true)
2、嵌入到导航控制器中
let hostingController = UIHostingController(rootView: MySwiftUIView())
navigationController?.pushViewController(hostingController, animated: true)
注意事项
UIHostingController 生命周期由 UIKit 管理,所以它和 SwiftUI 的 @State、@Environment 协作上可能会需要一些调优。
在 macOS 上有 NSHostingController(对应 NSViewController)。
在SwiftUI中如果想要使用UIKit控制器,则可以使用UIViewControllerRepresentable。
相关文章
macOS显示SwiftUI的桥接控制器NSHostingController:https://fangjunyu.com/2025/06/30/macos%e6%98%be%e7%a4%baswiftui%e7%9a%84%e6%a1%a5%e6%8e%a5%e6%8e%a7%e5%88%b6%e5%99%a8nshostingcontroller/