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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.