Chris
Chris

Reputation: 1013

Checking keyDown event.modifierFlags yields error

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!

Upvotes: 5

Views: 2035

Answers (3)

EDammen
EDammen

Reputation: 11

I was going to put in a comment, but wasn't able to.

In case someone (like me) comes across this article in the future, Swift has changed a little since 2015.

Swift 4:

theEvent.modifierFlags.contains(.command)

theEvent.modifierFlags.contains(.option)

theEvent.modifierFlags.contains([.command, .option]) NSLog("command and option keys down")

also; (.control) is for CTRL.

This is my particular code:

override func viewDidLoad()
{
    super.viewDidLoad()

    NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.keyDown, handler: myKeyDownEvent)

}


func myKeyDownEvent(event: NSEvent) -> NSEvent {

    if (event.keyCode == 121) && event.modifierFlags.contains([.command, .option]) {

        //Do what you want when PGDN + cmd + alt is pressed

    }

    return event
}

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236350

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")
    }
}

Upvotes: 2

Darren
Darren

Reputation: 25619

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")
    }

Upvotes: 14

Related Questions