UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to use UIKeyCommand to add keyboard shortcuts

Swift version: 5.6

Paul Hudson    @twostraws   

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.

The basic use of UIKeyCommand is this:

let search = UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(findFriends), discoverabilityTitle: "Find Friends")

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:

override var keyCommands: [UIKeyCommand]? {
    return [
        UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(findFriends), discoverabilityTitle: "Find Friends")
    ]
}

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:

override var keyCommands: [UIKeyCommand]? {
    if isAuthenticated {
        return [
            UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(findFriends), discoverabilityTitle: "Find Friends")
        ]
    } else {
        return nil
    }
}

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.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 7.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.