gpt4 book ai didi

uikit - addSubView SwiftUI View to UIKit UIView in Swift

转载 作者:行者123 更新时间:2023-12-03 07:35:54 27 4
gpt4 key购买 nike

我试图将SubView 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")
}

}

最佳答案

第一步:
使用 SwiftUI View 创建 UIHostingController 的实例

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

}
}
}

var child = UIHostingController(rootView: ContentView())

第 2 步:
将 UIHostingController 的实例作为 subview Controller 添加到 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)


您可以使用以下代码删除子 Controller
从 View Controller 中删除

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

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

关于uikit - addSubView SwiftUI View to UIKit UIView in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56631892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com