Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addSubview SwiftUI View to UIKit UIView in Swift

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

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

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")     }      } 
like image 398
Kathiresan Murugan Avatar asked Jun 17 '19 13:06

Kathiresan Murugan


People also ask

Can you use a SwiftUI view in UIKit?

SwiftUI works seamlessly with the existing UI frameworks on all Apple platforms. For example, you can place UIKit views and view controllers inside SwiftUI views, and vice versa.

How do I transfer data from SwiftUI to UIKit?

First, use binding to your input view. And for action use closure to get action from SwiftUI to UIKit. Here is a possible solution. override func viewDidLoad() { super.


1 Answers

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() 
like image 131
Imran Avatar answered Sep 22 '22 02:09

Imran