addSubView SwiftUI View to UIKit UIView in Swift

Kat*_*gan 28 uikit ios13 swiftui xcode11

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

错误:无法将“ContentView”类型的值转换为预期的参数类型“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")
    }

}
Run Code Online (Sandbox Code Playgroud)

Imr*_*ran 36

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

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

        }
    }
}

var child = UIHostingController(rootView: ContentView())
Run Code Online (Sandbox Code Playgroud)

第 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)

Run Code Online (Sandbox Code Playgroud)

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

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

// Finally, remove the child’s view from the parent’s
child.view.removeFromSuperview()
Run Code Online (Sandbox Code Playgroud)

  • 上面没有演示当您想直接从 UIView 使用 SwiftUI View 时会发生什么(即层次结构深处的 UIView 希望使用现有的 SwiftUI 视图,并且它无权访问其 UIViewController) (6认同)
  • 这个答案很好,谢谢。我知道苹果非常重视“从头开始重写你的应用程序”和“不与任何第三方代码连接”。但对于地球上的人们来说,如果苹果能够以无形的方式处理上述所有样板代码,那就太好了。然后我们就可以逐步将UIViews切换为Views了。 (3认同)
  • @Imran我想理解为什么你需要UIViewController?`UIHostingController(rootView: ContentView()).view` 你可以“基本上”将 swiftUI 视图转换为 UIView,一切似乎都有效,你能提供原因,为什么它“不支持”? (3认同)
  • @strangetimes SwiftUI 不支持这一点。您应该考虑重构您的代码,以便您的视图可以访问其控制器。 (2认同)