Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple action handlers of Buttons gets fired, only when the parent VStack is inside a List in SwiftUI

Tags:

xcode

ios

swiftui

Case 1:- When I have multiple Buttons in a VStack, on clicking of any one of them, the action handlers of both the buttons executes immediately, this happens only when the VStack is a child of List. For eg-

List {
            VStack {
                Button(action: { print("A") }) {
                Text("Button A")
                }

                Button(action: { print("B") }) {
                Text("Button B")
                }
            }
        }

Here when you click on any one Button(say Button B), the o/p is:- A B

Case 2:- Try that with just a VStack, it works fine. For eg-

VStack {
            Button(action: { print("C") }) {
            Text("Button C")
            }

            Button(action: { print("D") }) {
            Text("Button D")
            }
        }

Here when you click on any one Button(say Button D), the o/p is:- D

I am new to iOS programming, please help me understand where I am going wrong or is it an issue with SwiftUI?

like image 495
mohit kejriwal Avatar asked Sep 14 '19 17:09

mohit kejriwal


1 Answers

Set the button style to something different from the default, e.g., BorderlessButtonStyle()

struct Test: View {
  var body: some View {
    NavigationView {
      List {
        ForEach([
          "Line 1",
          "Line 2",
        ], id: \.self) {
          item in
          HStack {
            Text("\(item)")
            Spacer()
            Button(action: { print("\(item) 1")}) {
              Text("Button 1")
            }
            Button(action: { print("\(item) 2")}) {
              Text("Button 2")
            }
          }
        }
        .onDelete { _ in }
        .buttonStyle(BorderlessButtonStyle())
      }
      .navigationBarItems(trailing: EditButton())
    }
    .accentColor(.red)
  }
}
like image 115
Anton Avatar answered Nov 14 '22 20:11

Anton