Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior in SwiftUI Form container when using multiple buttons [duplicate]

Tags:

forms

swiftui

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")
                }
            }
        }
    }     
}
like image 824
andrewz Avatar asked Sep 07 '25 09:09

andrewz


1 Answers

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.

like image 71
Harshil Patel Avatar answered Sep 10 '25 00:09

Harshil Patel