Search code examples
iosswiftswiftuiview

How can I make each Button in the SwiftUI Form clickable?


I have stacked the buttons using HStack but whenever I click on any button I am only selecting the last defined button in this case I am selecting the 'Area' button. I think this should be an view overlapping issue.

struct ContentView: View {
    @State var selectedOption: String = ""
    var body: some View {
        Form{
            Section {
                        HStack(spacing: 1) {
                            Button ("Weight") {
                                selectedOption = "Weight"
                            }   .padding()
                                .foregroundColor(.mint)
                                .background(.black)
                                .font(.title3)
                                
                            Button ("Length") {
                                selectedOption = "Length"
                            }   .padding()
                                .foregroundColor(.mint)
                                .background(.black)
                                .font(.title3)
                            Button ("Temperature") {
                                selectedOption = "Temperature"
                            }   .padding()
                                .foregroundColor(.mint)
                                .background(.black)
                                .font(.title3)
                            Button ("Area") {
                                selectedOption = "Area"
                            }   .padding()
                                .foregroundColor(.mint)
                                .background(.black)
                                .font(.title3)
                        }
            }
            Section {
                if selectedOption == "Weight" {
                    Weight_View()
                }else {
                    Text (selectedOption)
                }
                
            }.frame(height: 500)
        }
    }
}```

Solution

  • The default Button style on iOS takes up the entire row of the Section inside the Form.

    To fix this, you can add the following to each button:

    .buttonStyle(.plain)
    

    After adding that, each Button is individually press-able.