在Swift中将UIUI的addSubView

在Swift中将UIUI的addSubView

本文介绍了在Swift中将UIUI的addSubView SwiftUI视图添加到UIKit UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个SwiftUI视图的SubView添加到UIView. self.view.addSubview(contentView)

I have tried to addSubView a SwiftUI View to UIView. self.view.addSubview(contentView)

请帮助我实现此用户界面.

Kindly help me to implement this 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的实例

Step 1:Create instances of UIHostingController by using SwiftUI View

struct ContentView : View {
    var body: some View {
        VStack {
            Text("Test")
            Text("Test2")

        }
    }
}

var child = UIHostingController(rootView: ContentView())

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

Step 2:Add instance of UIHostingController as a child view controller to 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)

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

You can use the following code to remove a child controllerRemove from view Controller

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

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

这篇关于在Swift中将UIUI的addSubView SwiftUI视图添加到UIKit UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:41