31

我曾尝试将addSubviewSwiftUI 视图转换为 UIView。self.view.addSubview(contentView)

错误:无法将“ContentView”类型的值转换为预期的参数类型“UIView”

请帮我实现这个用户界面。

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")
    }
    
}
4

1 回答 1

44

第 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()
于 2019-06-27T10:05:59.487 回答