Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Buttons inside HStack taking action of each other

Tags:

ios

swiftui

I have created a simple List with a horizontal stack view (label, button, button). each button has his own button action but when I run I can see tap on one button print two actions. breakpoint also comes inside both actions. her is my code gif

var body: some View {
    NavigationView {
        List {
            ForEach(self.heroViewModel.heros, id: \.self) { hero in
                Section(header: Text(hero.name)) {
                    ForEach(hero.movies, id: \.self) { movieName in
                        HStack {
                            Text(movieName)
                                .onTapGesture {
                                    return
                            }.frame(width: 150, height: 30, alignment: .leading)
                            Spacer()

                            Button(action: {
                                print("Rate us")
                            }, label: {
                                Text("Rate us")
                                    .background(Color.red)
                                }).padding()

                            Spacer()
                            Button(action: {
                                print("watch me")
                            }, label: {
                                Text("Watch")
                                    .background(Color.red)
                                }).padding()
                        }

                    }
                }
            }
        }.navigationBarTitle("Heros List")
    }
}
like image 346
Muhammad Shauket Avatar asked Oct 23 '19 03:10

Muhammad Shauket


1 Answers

Need to use onTapGesture instead of action like this way.

Button(action: {}) {
    Text("watch")
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.red)
.onTapGesture {
    print("watch")
}
like image 125
Muhammad Shauket Avatar answered Oct 11 '22 10:10

Muhammad Shauket