Button() Gotcha
I was implementing a filter feature on our app and decided to use Button()
wrapped in HStack
.
List {
HStack {
Button {
selectedFilter = .fullTime
let _ = print("Full Time Selected")
} label: {
Text("Full Time")
}
Button {
selectedFilter = .partTime
let _ = print("Part Time Selected")
} label: {
Text("Part Time")
}
Button {
selectedFilter = .gig
let _ = print("Gig Selected")
} label: {
Text("Gig")
}
}
}
When I tap on the Full Time
button, it will also call the other action tasks of the Part Time
and Gig
buttons. So it will output like
Full Time Selected
Part Time Selected
Gig Selected
where, it should only call or perform Full Time
action.
So I migrated to Text’s onTapGesture
List {
HStack {
Text("Full Time")
.onTapGesture {
selectedFilter = .fullTime
let _ = print("Full Time Selected")
}
Text("Part Time")
.onTapGesture {
selectedFilter = .partTime
let _ = print("Part Time Selected")
}
Text("Gig")
.onTapGesture {
selectedFilter = .gig
let _ = print("Full Time Selected")
}
}
}