Search code examples
iosswiftuiuikitaddsubview

Adding SwiftUI View to UIKit two UIViews VIA addSubView. One is adding but second is not


I am adding SwiftUI View 'TestView' to contentView1 and contentView2. But it is adding to contentView2 only. anyone please help me understand that why SwiftUI View isn't adding to contentView1. I have ensured that outlets are connected properly.

class ViewController: UIViewController {

    
    @IBOutlet var contentView1: UIView!
    @IBOutlet var contentView2: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let vc = UIHostingController(rootView: TestView())
        vc.view.translatesAutoresizingMaskIntoConstraints = false
        self.addChild(vc)
        contentView1.addSubview(vc.view)
        contentView2.addSubview(vc.view)
        vc.didMove(toParent: self)
    }
}

struct TestView: View {
    var body: some View {
        Text("SwiftUI")
            .onAppear(perform: {
                print("OnAppear Called")
            })
    }
}

enter image description here


Solution

  •         contentView1.addSubview(vc.view)
            contentView2.addSubview(vc.view)
    

    A given view can only have one parent view — you can't add the same view to two different views and expect it to show up twice. Create two separate views and add them to each of your content views, and you'll see them both.