Is it best to use multiple UIHostingControllers for nesting multiple SwiftUI views within a UIViewController?

56 Views Asked by At

Below is how you add a SwiftUI view to a UIViewController.

However, I have not seen any examples where someone adds two separate SwiftUI views to the same UIViewController.

Is the below approach advisable? I'm concerned that adding a lot of UIHostingController children could become memory intensive.

import UIKit
import SwiftUI

class CentralVC: UIViewController {
    
    lazy var rectangleView: UIView = {
        let hosting = UIHostingController(rootView: Rectangle().foregroundStyle(.orange))
        addChild(hosting)
        hosting.didMove(toParent: self)
        return hosting.view
    }()
    
    lazy var tabBarView: UIView = {
        let hosting = UIHostingController(rootView: TabBarView())
        addChild(hosting)
        hosting.didMove(toParent: self)
        return hosting.view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(rectangleView)
        view.addSubview(tabBarView)
        //viewDidLoad code
    }
    
    //Etc
}
0

There are 0 best solutions below