Ultimate Catalyst Guide

How do I support keyboard shortcuts?

released Fri, 05 Jul 2019
Swift Version 5.1

Keyboard shortcuts are implemented via the existing UIKeyCommand system on UIResponder. Here's a simple example of how your currently visible view controller can listen for Escape key presses by the user:

class MyKeyListeningViewController: UIViewController {

     override var keyCommands: [UIKeyCommand]? {

         return [UIKeyCommand(input: UIKeyCommand.inputEscape,

                              modifierFlags: [],

                              action: #selector(doCancelCommand(sender:)))

         ]

     }

}

Keep in mind that on macOS multiple views can easily be visible at the same time and the rules of the responder chain apply.