How to use UIKeyCommand to add keyboard shortcuts

Anyone who connects a keyboard to their iOS device is immediately able to take advantage of keyboard shortcuts – both at the system level and inside apps.

If you want your own apps to respond to shortcuts, as well as advertise those shortcuts to users, you need just one class: UIKeyCommand. You attach an array of these to each view controller that should respond to keyboard shortcuts, and iOS will take care of advertising and responding to them.

That takes four parameters in total: the input string to read, modifier flags, a selector, and a discoverability title. Let’s break them down…

First, the input string is the actual alphanumeric key that must be pressed in order to trigger your shortcut. You can specify literals here such as “f”, “t”, or “3”, or use constants such as UIKeyInputUpArrow, UIKeyInputLeftArrow, or UIKeyInputEscape.

Second, the modifier flags parameter accepts an option set of key modifiers. We’re using .command above to make Cmd+F a shortcut, but we could easily have used [.command, .shift] to make Cmd+Shift+F a shortcut.

Third, the selector parameter determines what code is run when the shortcut is triggered – the code above will call a findFriends() method on your view controller when Cmd+F is pressed. Because this is called from the Objective-C runtime you’ll need to mark it @objc, like this:

@objc func findFriends() {
// your code here
}

Finally, the discoverability title is there to control what is shown to users. Because there’s no natural on-screen place to discover keyboard shortcuts, iOS has a simple shortcut: users holding down the Cmd key will see an on-screen popup with your shortcuts and discoverability titles.

Once you’ve decided on your list of keyboard shortcuts, return them all from the keyCommands property of your view controller, like this:

iOS will automatically call that whenever the user holds down the Cmd key to show the shortcut list, or whenever they attempt to activate a shortcut. This means you can update it as often as you need, based on your app state:

Note: don’t try to override any built-in shortcuts, because iOS is always given the first opportunity to handle key commands – before they are routed to your app. So, built-in system events such as copy and paste will happen automatically even if you try to replace them.

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!