Reputation: 1654
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
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
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