Alvin Varghese Alvin Varghese - 3 months ago 22
Swift Question

Shift + Return key action in a Cocoa App

I have a

NSTextView
, whenever user presses on
Shift
+
Return
Key I should perform an action.

But the problem is that I could not figure out how to know whether the user pressed on
Return
key or not.

I have used this code to know whether user pressed on
Shift
key or not.

override func flagsChanged(theEvent: NSEvent) {

switch theEvent.modifierFlags.intersect(.DeviceIndependentModifierFlagsMask)
{
case NSEventModifierFlags.ShiftKeyMask :
print("shift key is pressed")
case NSEventModifierFlags.ControlKeyMask:
print("control key is pressed")
case NSEventModifierFlags.AlternateKeyMask :
print("option key is pressed")
case NSEventModifierFlags.CommandKeyMask:
print("Command key is pressed")
case NSEventModifierFlags.FunctionKeyMask:
print("Function key is pressed")

default:
print("no key or more than one is pressed")
}
}


But there is no option for Return key in
NSEventModifierFlags
.

Let me know your thoughts? How will I solve this?

Answer

I would suggest you to use the following approach to get the keyCode to understand when it is a shift, return key or whatever you want to detect in case of having the desired key, perform your logic.

import Cocoa

class YourWindow: NSWindow {
    override func keyDown(event: NSEvent) {
        super.keyDown(event)
        print("Caught a key down: \(event.keyCode)!")
    }
}

You can also use a keyUp event