swift - UIViewControllerRepresentable 要求类型 'some View' 和 'Never' 是等效的

标签 swift swiftui

使用 Xcode 11 GM Seed 编写一些 SwiftUI 代码,我遇到了一个我不明白的 Swift 错误。

struct MainViewController: View {
    var body: some View {
        VStack {
            Text("Hello World!")
        }
    }
}

extension MainViewController : UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<MainViewController>) -> UINavigationController {
        return UINavigationController()
    }

    func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<MainViewController>) {

    }
}

此报告:

'UIViewControllerRepresentable' requires the types 'some View' and 'Never' be equivalent

最佳答案

我错过了 ViewController 和 View 之间的分离。错误是说 View Controller 不能有返回 View 的主体。

这个有效:

struct MainView : View {
    var body: some View {
        VStack {
            Text("Hello World!")
        }
    }
}

struct MainViewController : UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<MainViewController>) -> UIHostingController<MainView> {
        return UIHostingController(rootView: MainView())
    }

    func updateUIViewController(_ uiViewController: UIHostingController<MainView>, context: UIViewControllerRepresentableContext<MainViewController>) {

    }
}

然后实例化它:

let viewController = UIHostingController<MainViewController>(rootView:MainViewController())

关于swift - UIViewControllerRepresentable 要求类型 'some View' 和 'Never' 是等效的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905693/

相关文章:

macos - 如何在 Swift 中使用 NSWindowOcclusionState.Visible

swift - AppStore 提交不适用于 RealmSwift 0.96.0/Cocoapods 0.39.0

ios - SwiftUI 中的 TextView 不仅显示更大的字体

json - 如何使用 SwiftyJSON 从具有多个对象和数组的 JSON 中读取值

ios - 用户出现在 Auth0 上但不出现在 AWS Cognito 身份池中

当 autoScales 设置为 true 时,iOS PDFView 会导致底层断言

ios - 在 SwiftUI 中,如何使手势在容器 View 之外处于非事件状态?

ios - Core Data + CloudKit 无法在其他设备上自动刷新?

swift - onDeleteCommand 菜单项始终启用

Swift:动态库和 AFNetworking