0

I am trying to create a situation in a SwiftUI Mac app where when I click a Button inside a parent view, only the Button's action is trigger—not any of the tap gestures attached to its parent.

Here is a simple example that reproduces the problem:

import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack(spacing: 30){
      Button("Button"){
        print("button clicked")
      }
      .padding(5)
      .background(Color.blue)
      .buttonStyle(PlainButtonStyle())
    }
    .frame(width: 500, height: 500)
    .background(Color.gray)
    .padding(100)

    .gesture(TapGesture(count: 2).onEnded {
      //Double click (open message in popup)
      print("double click")
    })
    .simultaneousGesture(TapGesture().onEnded {
      if NSEvent.modifierFlags.contains(.command){
        print("command click")
      }else{
        print("single click")
      }
    })
  }
}

Clicking the button triggers both button clicked and single click.

If you comment out the buttonStyle...

//.buttonStyle(PlainButtonStyle())

It works how I want it to. Only button clicked is fired.

It doesn't seem to matter which button style I use, the behavior persists. I really need a custom button style on the child button in my situation, so how do I get around this?

Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128

1 Answers1

1

If you replace your .simultaneousGesture with a regular .gesture it works for me – and still recognizes the outer single and double taps.

ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • Ah, fantastic! I thought I needed the `.simultaneousGesture` in order for the double-click gesture to work, but it seems to work fine with a regular `.gesture`. Thank you very much! – Clifton Labrum Mar 11 '22 at 19:06
  • :) I would have thought so too – as they are both TapGesture it seems to work. But be aware of the side effect that they now either detect the double tap or the single tap, not both (as it was before, a double tap would also trigger a single tap). – ChrisR Mar 11 '22 at 19:17