6

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

4

1 回答 1

10

UIView's 和UIViewController's 可以通过它们各自的类在 SwiftUI 中实现,UIViewRepresentableUIViewControllerRepresentable.

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

对不起,我的答案中缺少代码,我现在是 AFK。但是,最好的学习方法自己追踪和解决问题。希望这可以帮助!

更新

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

UIHostingController(rootView: MySwiftUIStruct())

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

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

于 2019-06-18T18:34:09.440 回答