Reputation: 1533
I have a SwiftUI List showing some cells. I want to put 3 buttons inside each cell. I want the user to able to tap each without selecting the cell or triggering the other buttons. The code I have now triggers all 3 buttons when the user taps the cell.
struct ContentView: View {
@State var names = ["Mohamed", "Ahmed", "Ali"]
var body: some View {
NavigationView {
List {
ForEach(names, id: \.self) { name in
NameCell(name: name)
}
}
.navigationBarTitle("Names")
}
}
}
struct NameCell: View {
let name: String
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text(name)
.font(.headline)
HStack {
Button("Action1") { print("action 1 tapped") }
Button("Action2") { print("action 2 tapped") }
Button("Action3") { print("action 3 tapped") }
}
}
}
}
Upvotes: 2
Views: 1022
Reputation: 4875
It looks a bug in SwiftUI
, while using button inside cell whole area is tappable. to solve this you can replace Button
with Text
and for action add TapGesture
to Text
.
Please try below code.
struct NameCell: View {
....
HStack(spacing: 10) {
Text("Action1").onTapGesture {
print("action 1 tapped")
}
Text("Action2").onTapGesture {
print("action 2 tapped")
}
Text("Action3").onTapGesture {
print("action 3 tapped")
}
}
....
}
Upvotes: 1