Home > Enterprise >  Swift UI Convert UIView to View: Return type of property 'body' requires that 'UIView
Swift UI Convert UIView to View: Return type of property 'body' requires that 'UIView

Time:05-31

I have a simple View in Swift:

import SwiftUI

import UIKit
import React

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func loadView() {
        loadReactNativeView()
    }

    func loadReactNativeView() {
        let jsCodeLocation = URL(string: "http://localhost:8081/index.bundle?platform=ios")!
        
        let rootView = RCTRootView(
            bundleURL: jsCodeLocation,
            moduleName: "YourApp",
            initialProperties: nil,
            launchOptions: nil
        )
        self.view = rootView
    }
    
}


struct ContentView: View {
    var body: some View {
        ViewController().view
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}



But the compiler complains: Return type of property 'body' requires that 'UIView' conform to 'View'

Can someone help me understand what am I doing wrong? I need to use UIViewController to present the View.

Here's my main implementation as given by Swift boilerplate:

import SwiftUI

@main
struct content_iosApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

CodePudding user response:

You cannot use UIView in a SwiftUI View. Even if you could, you wouldn't be able to see anything because when adding a UIView from a UIViewController to another you need to add that Controller as a child.

In order to use you ViewController in SwiftUI you need to wrap it in a UIViewControllerRepresentable like so:

struct SomeView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> ViewController {
        let viewController = ViewController()
        //additional setup
        return viewController
    }
    func updateUIViewController(_ uiViewController: ViewController, context: Context) {
        //update Content
    }
}

And your ContentView:

struct ContentView: View {
    var body: some View {
        SomeView()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
  • Related