Can't remember where I found this solution, but it does work. On the View that creates the TabView:
TabView(selection: $context.selectedTab) {
...generate your views normally.
}.onReceive(context.$selectedTab) { selection in
context.navToHome.toggle()
}
Where context is some environmentObject that you're passing to the affected views, and navToHome is a bool.
In your child views that you want to pop back to the root from:
@EnvironmentObject var context: YourContext
@Environment(\.presentationMode) private var presentationMode
var body: some View {
VStack {
Text("View here")
}.onChange(of: context.navToHome) { _ in
presentationMode.wrappedValue.dismiss()
}
}
You can also add other logic to the onChange that changes the behavior slightly. In my app, it only pops back to the root if it's tapped a second time, which allows viewing other tabs and retaining your state in one tab when you go back to it. Just a heads up, accessing @Environment(.presentationMode) is currently causing a bug where it causes the view to initialize multiple times, requiring you to do any initialization in other parts of code that only fire once, like onAppear. Hopefully this helps!