154

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
1

4 Answers 4

336

You can apply any button style (for example, .bordered, .borderless, .borderedProminent, etc.) EXCEPT for .automatic.

    List([1, 2, 3], id: \.self) { row in
        HStack {
            Button(action: { print("Button at \(row)") }) {
                Text("Row: \(row) Name: A")
            }
            .buttonStyle(.borderless)
            
            Button(action: { print("Button at \(row)") }) {
                Text("Row: \(row) Name: B")
            }
            .buttonStyle(.plain)
        }
    }
Sign up to request clarification or add additional context in comments.

14 Comments

This is the best solution if you need to maintain button animations (highlights, etc.)
Worked a charm, but why?
Yes. This is a real WTAF for me. How did you discover this?
@Jessy Spending a lot of time in the documentation.
I can't believe this is still an issue under iOS 17 ...
|
31

Seems to be a specific issue concerning Button when contained in a List row.

Workaround:

List {
  HStack {
    Text("One").onTapGesture { print("One") }
    Text("Two").onTapGesture { print("Two") }
  }
}

This yields the desired output.

You can also use a Group instead of Text to have a sophisticated design for the "buttons".

4 Comments

Unfortunately this bug isn't limited to Buttons within a List. I am able to reproduce the same issue with multiple NavigationLinks inside a HStack, inside of a List.
This is just a workaround. Using BorderlessButtonStyle() is the best way.
While this works, please keep in mind that this change has more implications. The accessibility API (for example for VoiceOver users) will no longer recognize "One" and "Two" as button. You would have to give it a button trait. I would say that adding a buttonStyle is the better way.
Adding tapGestures in general is really bad practice for accessibility reasons. Please do not do this.
11

One of the differences with SwiftUI is that you are not creating specific instances of, for example UIButton, because you might be in a Mac app. 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 .onTapGesture to have them act essentially as buttons, but you would lose the tap flash of the cell row and any other automatic button like features SwiftUI would give.

List {
    HStack {
        Text("One").onTapGesture {
            print("Button 1 tapped")
        }

        Spacer()

        Text("Two").onTapGesture {
            print("Button 2 tapped")
        }
    }
}

2 Comments

tapAction is no longer available (Xcode 11.2 beta). Use .onTapGesture()
Also you have to be careful as the tap gesture will only be applied to the visible area of the text itself. Every transparent area of your view won't be clickable.
7

You need to create your own ButtonStyle:

  struct MyButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
      configuration.label
        .foregroundColor(.accentColor)
        .opacity(configuration.isPressed ? 0.5 : 1.0)
    }
  }

  struct IdentifiableString: Identifiable {
    let text: String
    var id: String { text }
  }

  struct Test: View {
    var body: some View {
      List([
        IdentifiableString(text: "Line 1"),
        IdentifiableString(text: "Line 2"),
      ]) {
        item in
        HStack {
          Text("\(item.text)")
          Spacer()
          Button(action: { print("\(item.text) 1")}) {
            Text("Button 1")
          }
          Button(action: { print("\(item.text) 2")}) {
            Text("Button 2")
          }
        }
      }.buttonStyle(MyButtonStyle())
    }
  }

2 Comments

Actually, you do not need a custom style. Just use BorderlessButtonStyle()
This is a more general solution that just using one of the few built in styles. Just what I was looking for. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.