3

I am trying to use a key modifier with a tap gesture in my swiftUI view. I would like to have one action being performed when registering a tap gesture, and a separate action performed when holding command + tap gesture.

I tested the code used here to answer this exact question: Check state of Option-Key in SwiftUI (macOS)

I have tested this code inside a normal swiftUI view and it seems to work fine.

However, the view I would like to use this with is being shown on the touch bar. When testing with the touch bar, it will register a normal tap gesture, but will not register a tap gesture with a modifier. Is there something that I'm missing here? Thanks for the help. My code for the touch bar view is this:

struct SoundChartView: View {

@ObservedObject var modal = ChartModal()

var barWidth: CGFloat = 4.0
let barSpace: CGFloat = 1.0


var body: some View {
            
    GeometryReader { geo in
        
        ZStack {
            colorView().mask(
                ZStack {
                    // right channel
                    BarChart(vector: modal.vectorRight, barWidth: barWidth + 1)
                        .stroke(Color.white, lineWidth: barWidth)
                    // left channel
                    BarChart(vector: modal.vector, barWidth: barWidth + 1)
                        .stroke(Color.white, lineWidth: barWidth)
                }
            )
            .animation(
                Animation.easeOut(duration: 0.1)
            )
            
            .gesture(TapGesture().modifiers(.option).onEnded {
                    print("Do anyting on OPTION+CLICK")
                })
            .onTapGesture(count: 2, perform: {
                print("double tap")
            })
            .onTapGesture() {
                print("tapped")
            }
            .onLongPressGesture() {
                print("long press")
            }
Asperi
  • 228,894
  • 20
  • 464
  • 690
Jake F
  • 31
  • 4
  • I added an [answer](https://stackoverflow.com/a/66607280/15280114) to the other question you refer to that let's you test the state of any key you like from any context, so you aren't limited to a gesture providing event information. For example you could alter the text of a label when its displayed depending on the state of a key or key combination. – Chip Jarred Mar 12 '21 at 21:18

1 Answers1

10

You can use NSEvent.modifierFlags as fallback:

        .onTapGesture {
            print("Tap with option: \(NSEvent.modifierFlags.contains(.option))")
        }
Stephan Michels
  • 952
  • 4
  • 18