Im subclassing NSTextView and overriding keyDown. I want to detect command-key-combinations. Command-L, for example.
Apple's documentation indicates that you simply and the modifier flags (in the passed NSEvent) with NSEventModifierFlags.CommandKeyMask.
When I do so:
let ck = NSEventModifierFlags.CommandKeyMask
I receive an odd error:
Binary operator '&' cannot be applied to two 'NSEventModifierFlags' operands.
What's the deal? This is swift 2.0, xcode 7.
Thanks!
Apple's documentation indicates that you simply and the modifier flags
The documentation is still referring to C and Objective-C. Swift uses OptionSetType
, which does not use bitwise operators for checking flags.
Instead, use the contains()
method to check for one or more flags:
if theEvent.modifierFlags.contains(.CommandKeyMask) {
NSLog("command key down")
}
if theEvent.modifierFlags.contains(.AlternateKeyMask) {
NSLog("option key down")
}
if theEvent.modifierFlags.contains([.CommandKeyMask, .AlternateKeyMask]) {
NSLog("command and option keys down")
}
To check for a single key, use intersect
to filter out any unwanted flags, then use ==
to check for a single flag:
let modifierkeys = theEvent.modifierFlags.intersect(.DeviceIndependentModifierFlagsMask)
if modifierkeys == .CommandKeyMask {
NSLog("Only command key down")
}
NSEventModifierFlags is an optionSet in Swift 2.0. You can use contain method to check it contains the command modifier key
override func keyDown(theEvent:NSEvent) {
if theEvent.characters == "l" && theEvent.modifierFlags.contains(.CommandKeyMask) {
print("command-L pressed")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With