Search code examples
swiftswiftuiuikit

UIBarButtonItem with custom view doesn't work with UIHostingController


Assume we have UIWindow with UINavigationController as rootViewController.

window = UIWindow()
window!.makeKeyAndVisible()
let navigationController = UINavigationController()
window.rootViewController = navigationController

And then a basic UIHostingController with some dummy SwiftUI view.

let controller = UIHostingController(rootView: SomeView())
navigatonController.setViewControllers([controller], animated: false)

My problem is, that when I want to add UIBarButtonItem to UIHostingController it doesn't work and act like its nil (no frame in Debug View Hierarchy).

controller.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: CustomButton())

When I change the exact same code from UIHostingController to just UIViewController it works fine.

controller = UIViewController()

Any ideas how to fix this?


Solution

  • Use working variant with

    let controller = UIViewController()
    controller.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: CustomButton())
    
    

    and inject hosting controller as child of that controller

    let hosting = UIHostingController(rootView: SomeView())
    controller.view.addSubview(hosting.view)
    
    // set up view constraints here for `hosting.view`
    
    controller.addChild(hosting)
    hosting.didMove(toParent: controller)