addSubView SwiftUI View to UIKit UIView in Swift

后端 未结 1 942
Happy的楠姐
Happy的楠姐 2020-12-09 16:51

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

Error: Cannot convert value of type \'ContentView\

1条回答
  •  感情败类
    2020-12-09 17:13

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

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

    0 讨论(0)
提交回复
热议问题