Search code examples
swiftuiuihostingcontroller

SwiftUI - How to access UIHostingController from SwiftUI


I have SwiftUI page, it's being navigated from UIKit view. I want to set a title to this page, what I'm doing is

// code of UIKit view
let controller = UIHostingController(rootView: SwiftUIView())
controller.title = "title"
MyNavigationManager.present(controller)

Is there a way I can access the hosting controller within SwiftUI?

Then I could write code like self.hostingController?.title = "title"


Solution

  • Here is a demo of possible approach - to use external configuration wrapper class to hold weak link to controller and inject it into SwiftUI view (as alternate it is also possible to make it ObservableObject to combine with other global properties and logic).

    Tested with Xcode 12.5 / iOS 14.5

    class Configuration {
        weak var hostingController: UIViewController?    // << wraps reference
    }
    
    struct SwiftUIView: View {
        let config: Configuration   // << reference here
    
        var body: some View {
            Button("Demo") {
                self.config.hostingController?.title = "New Title"
            }
        }
    }
    
    let configuration = ExtConfiguration()
    let controller = UIHostingController(rootView: SwiftUIView(config: configuration))
    
    // injects here, because `configuration` is a reference !!
    configuration.hostingController = controller
    
    controller.title = "title"
    MyNavigationManager.present(controller)