UIViewControllerRepresentable 要求类型“some View”和“Never”等效

ste*_*vex 7 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>) {

    }
}
Run Code Online (Sandbox Code Playgroud)

这篇报道:

'UIViewControllerRepresentable' requires the types 'some View' and 'Never' be equivalent
Run Code Online (Sandbox Code Playgroud)

ste*_*vex 6

我错过了 ViewController 和 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>) {

    }
}
Run Code Online (Sandbox Code Playgroud)

然后实例化它:

let viewController = UIHostingController<MainViewController>(rootView:MainViewController())
Run Code Online (Sandbox Code Playgroud)