4
votes

I have a SwiftUI NavigationView in which I push to a to UIViewControllerRepresentable conforming UIViewController. The navigation view naturally adds its back button. However, all navigation bar buttons that I set in the pushed-to view controller are also gone.

The code for adding the item is nothing new and works just fine if I push from a good ol' UIKit View Controller:

navigationItem.rightBarButtonItem = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(filterItemTapped(button:)))

My theory is that they haven't wired up bridging between NavigationView and UIViewController's navigation items, but maybe somebody knows a workaround.

1
Clarification question (which may mean you need to add more code to reproduce): UIViewControllerRelatable is a View inside a SwiftUI app. As is your NavigationView. But you make it sound like you want some kind of navigation bar in your UIViewController, as in UIKit? If so, maybe you need to rethink something - maybe even the reverse (put your SwiftUI View into your UIKit app).dfd
Final thoughts. If you want to "push" values/data into your UIViewController, that's more Combine than SwiftUI (but yeah, it's both). But if you want to push a NavigationBar, which is a View, then yes you need to do the reverse - make a UIKit app and import the views.dfd
Yeah I just wanted to have a SwiftUI View with its native bar buttons and a UIKit ViewController with its own native bar buttons in the same App. But your answer made me understand that that's not possible. What I ended up doing is to wrap my UIViewController in a SwiftUI View and set those bar buttons on it. Works like a charm. So thanks man.hoshy

1 Answers

-4
votes

In your UIViewControllerRepresentable, wrap your UIViewController with a UINavigationController.

struct CustomUIViewControllerRepresentation: UIViewControllerRepresentable {
    typealias UIViewControllerType = UINavigationController

    func makeUIViewController(context: Context) -> UINavigationController {
        let viewController = CustomUIViewController()
        let navigationController = UINavigationController(rootViewController: viewController)
        return navigationController
    }

    func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {

    }
}