I've been adopting SwiftUI into a legacy UIKit app. Individual views work great, but when I try to intermix SwiftUI and UIKit navigation things go bad fast. What is the best practice here?
Thanks for the question!
My recommendation would be to not intermix SwiftUI and UIKit navigation within the same ‘stack’ (NavigationStack in SwiftUI, UINavigationController in UIKit) - having the 2 frameworks both trying to mutate the same stack can run into issues. (Apps also sometimes try mixing and matching by putting one stack inside the other and hiding the navigation bar, but I would say that’s an anti-pattern and can cause issues with transitions and/or items going into the wrong bar)
In terms of how to accomplish this when mixing frameworks: if you use a UINavigationController and want to push a view written in SwiftUI, you can push a UIHostingController onto the nav controller that contains the SwiftUI view. If you use a NavigationStack and want to push a UIViewController, you can push a SwiftUI view that contains a UIViewControllerRepresentable.
Regardless of which framework you pick, I’d structure your navigation data model in a way that is state-driven and framework agnostic. This gives the maximum flexibility and helps with things like testing
It’s fine to use both NavigationStack and UINavigationController in the same app, though, provided they're for separate stacks - one example would be your root-level navigation is in UIKit with a UINavigationController, and when you’re building a new flow, you present a SwiftUI sheet with a NavigationStack for navigation within the sheet