How to detect command + arrow key in a Swift 3 Cocoa app

Viewed 1798
override func keyDown(with event: NSEvent) {
    switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
    case [.command] where event.characters == "9":
        print("command-9")
    case [.command] where event.keyCode == 123:
        print("command-left arrow") // problem: this never executed
    default:
        break
    }
}

Above is want I have tried. command-9 works like a charm. But command - arrow doesn't work.

It seems that if you press command - arrow, the modifier flag is not command. I searched the internet but couldn't get it work.

3 Answers

Swift 5 Solution - The below code also works on Mac Catalyst

override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
    guard let key = presses.first?.key else { return }
    if key.modifierFlags.contains(.command) {
        switch key.keyCode {
        case .keyboardUpArrow:
            print("command + up arrow")
        case .keyboardDownArrow:
            print("command + down arrow")
        case .keyboardLeftArrow:
            print("command + left arrow")
        case .keyboardRightArrow:
            print("command + right arrow")
        default:
            break
        }
    }
}
Related