如何在 SwiftUI 中使用 UIViewController 和 UIView?

How can I use UIViewController and UIView in SwiftUI?

我尝试将自定义 UIViewController 集成到 Swift 应用程序中,但我无法将其与 SwiftUI 元素集成,例如 Text( ).我收到此错误:函数声明了一个不透明的 return 类型,但其主体中没有 return 语句可从中推断出基础类型。我应该使用 UIView 而不是 UIViewController 吗?

UIViewUIViewController 可以通过各自的 类、UIViewRepresentableUIViewControllerRepresentable 在 SwiftUI 中实现。

Apple 的 SwiftUI 教程介绍了这一点,以及将 UIKit 集成到 SwiftUI 中的其他方法。

SwiftUI 教程: https://developer.apple.com/tutorials/swiftui/tutorials

使用 UIViewRepresentable 将 UIView 放入 SwiftUI 中: https://developer.apple.com/tutorials/swiftui/creating-and-combining-views ^ 参见第 5 节,它使用 MKMapView 作为 UIView

与 UIKit 接口: https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit

抱歉,我的回答中缺少代码,我现在挂机了。然而,学习 的最佳方法是 自己追踪并解决问题。希望这对您有所帮助!

更新

如果您想将 SwiftUI 集成到现有的 UIKit 应用程序中,请考虑使用 UIHostingController。它的工作方式如下:

UIHostingController(rootView: MySwiftUIStruct())

https://developer.apple.com/documentation/swiftui/uihostingcontroller

它允许您在 UIKit 应用程序中放置 SwiftUI 内容,就像在其中放置 UIView 或 UIViewController 一样。