在 Swift 中将 SwiftUI 视图添加到 UIKit UIView [英] addSubview SwiftUI View to UIKit UIView in Swift

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

问题描述

我尝试将 SwiftUI 视图 addSubview 加入 UIView.self.view.addSubview(contentView)

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

错误:无法将ContentView"类型的值转换为预期的参数类型'界面视图'

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

请帮助我实现这个 UI.

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

推荐答案

第一步:使用 SwiftUI 视图创建 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 controller Remove 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 中将 SwiftUI 视图添加到 UIKit UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆