Say I have a List
and two buttons in one row, how can I distinguish which button is tapped without the entire row highlighting?
For this sample code, when any one of the buttons in the row is tapped, both button's action callbacks are invoked.
// a simple list with just one row List { // both buttons in a HStack so that they appear in a single row HStack { Button { print("button 1 tapped") } label: { Text("One") } Button { print("button 2 tapped") } label: { Text("Two") } } }
When only one of buttons is tapped once, I see the callbacks for both buttons being called, which is not what I want:
button 1 tapped button 2 tapped
With SwiftUI, you are requesting a button type thing. In this case since you are in a list row, the system gives you a full size, tap anywhere to trigger the action, button. And since you've added two of them, both are triggered when you tap anywhere. You can add two separate Views and give them a .
To connect the action to multiple buttons: in Interface Builder, right-click ViewController in the view hierarchy, then left-click to drag the action connection to each button.
SwiftUI's button is similar to UIButton , except it's more flexible in terms of what content it shows and it uses a closure for its action rather than the old target/action system. To create a button with a string title you would start with code like this: Button("Button title") { print("Button tapped!") }
Probably the simplest way to build a list is to create a new SwiftUI view and wrap the Hello World text in a List: struct StaticListView: View { var body: some View { List { Text("Hello, world!") } } } To add more items to the list, we can just add another line: List { Text("Hello, world!") Text("Hello, SwiftUI!") }
You need to use BorderlessButtonStyle() or PlainButtonStyle().
List([1, 2, 3], id: \.self) { row in HStack { Button(action: { print("Button at \(row)") }) { Text("Row: \(row) Name: A") } .buttonStyle(BorderlessButtonStyle()) Button(action: { print("Button at \(row)") }) { Text("Row: \(row) Name: B") } .buttonStyle(PlainButtonStyle()) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With