3

Given the code below I expected to see selection be ZERO after tapping on the ZERO button, but it always is ONE. In fact, I need not tap on the button name, but in the middle of the row, and the selection will still be ONE. This is unexpected behavior and possibly a bug. Anyone has an explanation and/or workaround for this? Using iOS 14.0 and Xcode 12.2

struct TestForm : View {
    
    @State var selection = ""
    
    var body : some View {
        Form {
            Text("selection: \(selection)")
            HStack {
                Button(action: {
                    selection = "ZERO"
                }) {
                    Text("ZERO")
                }
                Spacer()
                Button(action: {
                    selection = "ONE"
                }) {
                    Text("ONE")
                }
            }
        }
    }     
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
andrewz
  • 4,729
  • 5
  • 49
  • 67

1 Answers1

2

Use PlainButtonStyle().

struct ContentView: View {
    @State var selection = ""
    
    var body : some View {
        Form {
            Text("selection: \(selection)")
            HStack {
                Button(action: {
                selection = "ZERO"
            }) {
                Text("ZERO")
                .foregroundColor(.blue)
            }.buttonStyle(PlainButtonStyle())
                
            Spacer()
                
            Button(action: {
                selection = "ONE"
            }) {
                Text("ONE")
                .foregroundColor(.blue)
            }.buttonStyle(PlainButtonStyle())
                    
            }
        }
    }
}

I added .foregroundColor(.blue) to button text because if you add .buttonStyle(PlainButtonStyle()) to your button it will make your buttons look like plain text.

Harshil Patel
  • 1,318
  • 1
  • 7
  • 26
  • This works as expected, but I still don't understand why this works and the other approach doesn't -- why does using PlainButtonStyle() matter? – andrewz Nov 26 '20 at 22:01
  • I followed the link to a similar question and got this quote which answers my question: "In this case since you are in a list row, the system gives you a full size, tap anywhere to trigger the action, button. And since you've added two of them, both are triggered when you tap anywhere." ... https://stackoverflow.com/questions/56561064/swiftui-multiple-buttons-in-a-list-row – andrewz Nov 26 '20 at 22:04
  • @andrewz In that post Jonathan [answered](https://stackoverflow.com/a/56693263/14073532) why (the same thing you quoted) :) – Harshil Patel Nov 26 '20 at 22:09