Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Multiple Buttons in a List row

Tags:

ios

swift

swiftui

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 
like image 863
Bradley Mackey Avatar asked Jun 12 '19 11:06

Bradley Mackey


People also ask

How do I add multiple buttons in SwiftUI?

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 .

How do I select multiple buttons in Swift?

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.

How do I use buttons in SwiftUI?

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!") }

How do I create a list in SwiftUI?

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!") }


1 Answers

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())         }     } 
like image 58
Ramis Avatar answered Sep 20 '22 15:09

Ramis