ios – 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

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img