addSubview SwiftUI View to UIKit UIView in Swift

addSubview SwiftUI View to UIKit UIView in Swift

我已经尝试 addSubview SwiftUI View 到 UIView。 self.view.addSubview(contentView)

Error: Cannot convert value of type 'ContentView' to expected argument type 'UIView'

请帮助我实现这个 UI。

import UIKit
import SwiftUI

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.lightGray
        
        let contentView = ContentView()
        view.addSubview(contentView) // Error: Cannot convert value of type 'ContentView' to expected argument type 'UIView'
    }


}


struct ContentView: View {
    var body: some  View {
        Text("Hello world")
    }
    
}

第 1 步: 使用 SwiftUI View

创建 UIHostingController 实例
struct ContentView : View {
    var body: some View {
        VStack {
            Text("Test")
            Text("Test2")

        }
    }
}

var child = UIHostingController(rootView: ContentView())

第 2 步: 将 UIHostingController 的实例作为子视图控制器添加到 Any UIKit ViewController

var parent = UIViewController()
child.view.translatesAutoresizingMaskIntoConstraints = false
child.view.frame = parent.view.bounds
// First, add the view of the child to the view of the parent
parent.view.addSubview(child.view)
// Then, add the child to the parent
parent.addChild(child)

您可以使用以下代码删除子控制器 从视图控制器中移除

// Then, remove the child from its parent
child.removeFromParent()

// Finally, remove the child’s view from the parent’s
child.view.removeFromSuperview()