Alvin Varghese Alvin Varghese - 1 year ago 89
Swift Question

Shift + Return key action in a Cocoa App

I have a

, whenever user presses on
Key I should perform an action.

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

I have used this code to know whether user pressed on
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")

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

But there is no option for Return key in

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

Answer Source

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) {
        print("Caught a key down: \(event.keyCode)!")

You can also use a keyUp event