在按下手势识别器的处理程序中,我试图找出是否按下了CMD或Shift,如下所示:
- (void)handlePress:(NSPressGestureRecognizer*)gr {
NSEventModifierFlags flags = [[NSApp currentEvent] modifierFlags];
if (flags & NSCommandKeyMask) {
NSLog(@"CMD pressed");
}
}
然而,该标志只能在keyDown或keyUp事件处理程序方法中正确设置。NSGestureRecognizer似乎没有暴露事件对象,因此我从NSApp获得currentEvent。我错过了什么?
您可以这样使用NSGestureRecognizerDelegate
,而不是子类化:
extension ViewController : NSGestureRecognizerDelegate
{
func gestureRecognizer(_ gestureRecognizer: NSGestureRecognizer,
shouldAttemptToRecognizeWith event: NSEvent) -> Bool {
return event.modifierFlags.contains(.command)
}
}
从技术上讲,这将只识别在鼠标下移时按住的修饰键,但从UI的角度来看,这可能是您想要的。
尝试创建NSPressGestureRecognizer子类,从鼠标按下事件中收集修饰符标志。
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
}
}