I have a simple TabView:
TabView {
NavigationView {
VStack {
NavigationLink(destination: Text("Detail")) {
Text("Go to detail")
}
}
}
.tabItem { Text("First") }
.tag(0)
Text("Second View")
.tabItem { Text("Second") }
.tag(1)
}
When I go to the detail view on tab 1, switch to tab 2 then switch back to tab 1 I would assume to go back to the detail view (a basic UX found everywhere in iOS). Instead it resets to the root view of tab 1.
Since SwiftUI doesn't look to support this out of the box, how do I work around this?
Here's a simple example of how to preserve state for a navigation stack with a list of items at the root:
So, this does "preserve" the detail view when switching tabs, but only by visibly pushing the detail view when switching back to tab 1. I have been unsuccessful at disabling this with, for example,
.animation()
.In addition, you pretty much have to override the navigation bar items in the
DetailView
, because the default back button behaves oddly (comment out the.navigationBarItems()
line to see what I mean).With those caveats, this does qualify as a workaround.
The not so obvious solution here was to actually not use SwiftUI. To get the UIKit behaviour I wrapped a UIKit
UITabBarController
in a SwiftUIUIViewControllerRepresentable
like in this example: https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit.I show a basic implementation here. The full up to date implementation is on github: https://gist.github.com/Amzd/2eb5b941865e8c5cccf149e6e07c8810
Wrap the UIKit UITabBarController in a SwiftUI view:
Example usage: