Comportamiento inesperado en el contenedor SwiftUI Form cuando se utilizan varios botones [duplicar]

Nov 27 2020

Dado el código a continuación, esperaba ver la selección ZEROdespués de tocar el ZERObotón, pero siempre lo es ONE. De hecho, no necesito tocar el nombre del botón, sino en el medio de la fila, y la selección seguirá estando ONE. Este es un comportamiento inesperado y posiblemente un error. ¿Alguien tiene una explicación y / o solución para esto? Usando iOS 14.0 y 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")
                }
            }
        }
    }     
}

Respuestas

2 HarshilPatel Nov 27 2020 at 04:44

Utilice 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())
                    
            }
        }
    }
}

Agregué .foregroundColor(.blue)al texto del botón porque si agrega .buttonStyle(PlainButtonStyle())a su botón, los botones se verán como texto sin formato.