Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking keyDown event.modifierFlags yields error

Tags:

macos

swift

cocoa

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!

like image 609
Chris Avatar asked Oct 15 '15 21:10

Chris


2 Answers

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")
    }
like image 148
Darren Avatar answered Sep 30 '22 06:09

Darren


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")
    }
}
like image 24
Leo Dabus Avatar answered Sep 30 '22 08:09

Leo Dabus