iamjustaprogrammer
iamjustaprogrammer

Reputation: 1654

How to detect if the CMD or Shift key has been pressed during a NSPressGestureRecognizer event?

In the handler of an press gesture recognizer I try to find out if CMD or Shift has been pressed, like this:

- (void)handlePress:(NSPressGestureRecognizer*)gr {
    NSEventModifierFlags flags = [[NSApp currentEvent] modifierFlags];
    if (flags & NSCommandKeyMask) {
        NSLog(@"CMD pressed");
    }
}

However the flag is only set correctly in a keyDown or keyUp event handler method. NSGestureRecognizer doesn't seem to expose the event object thus I get the currentEvent it from NSApp. What am I missing?

Upvotes: 1

Views: 1168

Answers (2)

Taylor
Taylor

Reputation: 6410

Instead of subclassing, you can use NSGestureRecognizerDelegate like so:

extension ViewController : NSGestureRecognizerDelegate
{
    func gestureRecognizer(_ gestureRecognizer: NSGestureRecognizer,
                           shouldAttemptToRecognizeWith event: NSEvent) -> Bool {
        return event.modifierFlags.contains(.command)
    }
}

Technically, this will only recognize modifier keys held at the time the mouse went down, but from a UI standpoint, that could be what you want anyway.

Upvotes: 2

DownEast
DownEast

Reputation: 1

Try subclassing NSPressGestureRecognizer to collect the modifier flags from the mouse down event.

class PressGestureRecognizer: NSPressGestureRecognizer {
var modifierFlags = NSEventModifierFlags (rawValue: 0)

override func flagsChanged (with event: NSEvent) {
    super.flagsChanged (with: event)
    modifierFlags = event.modifierFlags
}

override func mouseDown (with event: NSEvent) {
    super.mouseDown (with: event)
    modifierFlags = event.modifierFlags
}

}

Upvotes: 0

Related Questions