ios - 如何在 SwiftUI 中使用 UIViewController 和 UIView?

标签 ios swift uikit swiftui xcode11

我曾尝试将自定义 UIViewController 集成到 Swift 应用程序中,但无法将其与 SwiftUI 元素(如 Text())集成。我收到此错误:函数声明了一个不透明的返回类型,但其主体中没有可从中推断基础类型的返回语句。我应该使用 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 接口(interface): 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 一样。

关于ios - 如何在 SwiftUI 中使用 UIViewController 和 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56654546/

相关文章:

cocoa - Xcode中的Interface Builder 4.如何生成类文件?

ios - Swift MKMapView 多边形叠加故障

ios - 在自定义 View 中定义点击手势时出现无法识别的选择器错误 [Swift]

ios - NSNotFound 究竟是什么?

ios - MPMoviePlayerController 再次向后缓冲视频

ios - 如何使用 UIPreviewParameters 指定一系列文本作为 UIContextMenuInteraction 的突出显示预览,而不隐藏 View 的其余部分?

swift - UIView 中神秘的 UIColor 行为以及 Swift 中的一般情况

ios - 安装 Xcode 9 后,Iphone 模拟器上的 Sprite kit 动画帧每秒少于 10。有什么办法可以解决这个问题

ios - 需要有关 NSURLConnection 的帮助

ios - 如何在 NSString 中获取单词或音节的索引