Add button to list cell

Viewed 1448

How can I add a button to my List cell?

var body: some View{
    List {
        VStack {
            Button(action: {
                print("Hello, World!")
            }, label: {
                Text("Hello, World!")
            })
            Text("Something irrelevant")
        }
    }
}

The above prints Hello, World! when I tap Hello, World!, but also when I tap Something irrelevant. I only want it to happen when tapping the button, how would I go about doing this?

1 Answers

In SwiftUI, when you tap a cell in a list, the action parameter of each child button is called. If this is not the behaviour you want, you need to configure the tapAction property of the button, while leaving the action parameter blank.

In this case, your code would like this:

 var body: some View{
        List {
            VStack {
                Button(action: {

                }, label: {
                    Text("Hello, World!")
                }).tapAction {
                    print("Hello, World!")
                }
                Text("Something irrelevant")
            }
        }
    }
Related