Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swiftui

Writing some SwiftUI code using the Xcode 11 GM Seed, and I've run into a Swift error I don't understand.

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>) {

    }
}

This reports:

'UIViewControllerRepresentable' requires the types 'some View' and 'Never' be equivalent
like image 829
stevex Avatar asked Sep 12 '19 11:09

stevex


Video Answer


1 Answers

I was missing the separation between ViewController and View. The error was saying that a view controller can't have a body that returns a view.

This works:

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>) {

    }
}

And then to instantiate it:

let viewController = UIHostingController<MainViewController>(rootView:MainViewController())
like image 84
stevex Avatar answered Oct 16 '22 07:10

stevex