In the app I’m working on I’m trying to navigate to the second level of a navigation link chain from elsewhere in the app. To do that I’m attempting to utilize tag/selection to specify where I want to navigate.
The code you can see below is an example project that shows the weird bugs that arise.
import SwiftUI
@main
struct NavigationLinkTestingApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(ViewModel())
}
}
}
class ViewModel: ObservableObject {
@Published var selection: String? = nil
}
struct ContentView: View {
@EnvironmentObject var model: ViewModel
var body: some View {
NavigationView {
VStack(spacing: 30) {
NavigationLink(tag: "screen2", selection: $model.selection) {
Screen2()
} label: {
EmptyView()
}
.isDetailLink(false)
Button("Go to Screen 2") {
model.selection = "screen2"
}
Button("Go to screen 3") {
model.selection = "link3"
}
}
.navigationTitle("This is screen 1")
}
}
}
struct Screen2: View {
@EnvironmentObject var model: ViewModel
var body: some View {
VStack(spacing: 30) {
NavigationLink(tag: "screen3", selection: $model.selection) {
Screen3()
} label: {
EmptyView()
}
.isDetailLink(false)
Button("Go to Screen 3") {
model.selection = "screen3"
}
}
.navigationTitle("This is screen 2")
}
}
struct Screen3: View {
@EnvironmentObject var model: ViewModel
var body: some View {
Text("This is screen 3")
}
}
The two bugs I noticed when running this are:
- The “Go to screen 3” button at the top level does nothing even though it just dose change the value in the ViewModel.
- Navigating to screen3 from screen2 only holds the view for a split second before popping back out to the top level.
Is there a way to fix this? Is this even the best way to go about solving this navigation problem?