In SwiftUI, when I place multiple NavigationLink
views directly inside a HStack
, then put this HStack
inside a List
, clicking one link triggers all NavigationLink views, causing unexpected navigation behavior.
struct ContentView: View {
var body: some View {
NavigationStack {
List{
HStack {
NavigationLink(value: 1) {
Text("navigation 1")
}
NavigationLink(value: 2) {
Text("navigation 2")
}
NavigationLink(value: 3) {
Text("navigation 3")
}
}
}
.navigationDestination(for: Int.self) { value in
switch value {
case 0,1,2,3,4,5,6,7,8,9:
Text("Page \(value)")
default:
Text("Page not found \(value)")
}
}
}
}
}
Expected Behavior:
Actual Behavior:
And if this HStack
is not embeded in a List
, everything will work as expected.
struct ContentView: View {
var body: some View {
NavigationStack {
HStack {
NavigationLink(value: 1) {
Text("navigation 1")
}
NavigationLink(value: 2) {
Text("navigation 2")
}
NavigationLink(value: 3) {
Text("navigation 3")
}
}
.navigationDestination(for: Int.self) { value in
switch value {
case 0,1,2,3,4,5,6,7,8,9:
Text("Page \(value)")
default:
Text("Page not found \(value)")
}
}
}
}
}
The HStack
activates all the links at once, because
the List
gets the tap.
To fix it
try this approach using Button
and NavigationPath
instead.
struct ContentView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
VStack {
HStack {
Button("navigation 1") { path.append(1) }
Button("navigation 2") { path.append(2) }
Button("navigation 3") { path.append(3) }
}
}
.navigationDestination(for: Int.self) { value in
Text("Page \(value)")
}
}
}
}
EDIT-1:
just using a ScrollView
struct ContentView: View {
var body: some View {
NavigationStack {
ScrollView {
HStack {
NavigationLink("navigation 1", value: 1)
NavigationLink("navigation 2", value: 2)
NavigationLink("navigation 3", value: 3)
}
}
.navigationDestination(for: Int.self) { value in
Text("Page \(value)")
}
}
}
}