您确实需要将视图控制器包装在符合 UIViewControllerRepresentable 协议的 SwiftUI 结构中。这允许您在 SwiftUI 视图层次结构中使用 UIKit 视图控制器。
有一个非常相似的协议,UIViewRepresentable,它适用于不是控制器的 UIKit 视图——它的工作方式几乎完全相同。
因此,如果您的 UIKit 视图控制器名为 MyViewController,我们可以将其包装在一个名为 MyView 的 Swift 视图中。我们必须实现两种方法:
struct MyView: UIViewControllerRepresentable {
// autocomplete will give a return value of `some UIViewController`
// but if you replace that with your controller's class name, it
// makes everything clearer
func makeUIViewController(context: Context) -> MyViewController {
// do basic setup in here
return MyViewController()
}
func updateUIViewController(
// you have to specify your UIKit class name here too
_ uiViewController: MyViewController,
context: Context
) {
// do the main configuration of your view controller in here,
// especially if there's SwiftUI state you need the controller
// to react to
///
// You don't have to do anything in this method, but you still have
// to include it. Leave it empty if you're not configuring anything
}
}
这就是你要让你的控制器版本在 SwiftUI 的视图层次结构中工作所要做的一切。您必须记住直接使用 SwiftUI 包装器而不是 UIKit 视图控制器,例如:
NavigationLink{
MyView()
} label: {
Text("XXX")
}
如果您需要将信息传递给视图控制器以进行设置,让它响应 SwiftUI 状态的变化,或者如果您想要根据控制器中的事件或操作更新状态,则还有更多工作要做。但我认为这超出了你的问题范围。