UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Buttons in a form/section

Forums > SwiftUI

I'm not sure if buttons in a form are good UI practise but can someone explain the following. If I have the following very simple code each button responds seperately:

struct ContentView: View {
    var body: some View {
        HStack {
            Button("Button 1") {
                print("Button 1")
            }
            Spacer()
            Button("Button 2") {
                print("Button 2")
            }
        }
    }
}

If I change the code to the following which ever button is pressed it prints "Button 1" and "Button 2"

struct ContentView: View {
    var body: some View {
        Form {
            Section(header: Text("Test")) {
                HStack {
                    Button("Button 1") {
                        print("Button 1")
                    }
                    Spacer()
                    Button("Button 2") {
                        print("Button 2")
                    }
                }
            }
        }
    }
}

Additionally if I add some text that responds to:

struct ContentView: View {
    var body: some View {
        Form {
            Section(header: Text("Test")) {
                VStack {
                    HStack {
                        Button("Button 1") {
                            print("Button 1")
                        }
                        Spacer()
                        Button("Button 2") {
                            print("Button 2")
                        }
                    }

                    Text("Some Text")
                        .font(.headline)
                }
            }
        }
    }
}

It's like the section has become one button and I can press anywhere and get the same response.

4      

This is a known issue. (Whether it is intended behavior or not, I cannot say.) You can fix it by using the modifier .buttonStyle(BorderlessButtonStyle()). You can attach it either to each button individually or to the enclosing HStack (in which case it will apply to all buttons within that stack).

11      

Well I doubt I'd have found that solution by searching. Thank you.

4      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.