UIKeyCommand
UIKeyCommand
is a UIKit class introduced in iOS 7 that enables developers to add keyboard shortcuts to iOS apps, enhancing user productivity, especially on devices with external keyboards (e.g., iPad with Smart Keyboard). It allows apps to respond to key combinations, integrating seamlessly with the iOS responder chain.
Purpose
- Keyboard Shortcuts: Defines key combinations (e.g., Command + S) to trigger actions.
- Accessibility: Improves app usability for users relying on keyboards.
- Integration: Works within the UIKit responder chain, making it easy to implement in view controllers or views.
Key Features
- Key Combinations: Supports single keys or modified keys (e.g., Command, Shift, Option).
- Action Handling: Triggers a specified selector when the key command is activated.
- Discoverability: On iOS 13 and later, shortcuts can be displayed in a discoverability overlay when holding the Command key.
- Customization: Allows dynamic enabling/disabling and input modification.
Basic Usage
UIKeyCommand
is created with an input string, modifier flags, and an action selector, then added to a view controller or responder via the keyCommands
property.
Example
import UIKit
class ViewController: UIViewController {
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "s", modifierFlags: .command, action: #selector(saveAction), discoverabilityTitle: "Save")
]
}
@objc func saveAction(_ sender: UIKeyCommand) {
print("Save action triggered")
}
}
Key Points
- Initialization: Use
UIKeyCommand(input:modifierFlags:action:)
orUIKeyCommand(title:action:input:modifierFlags:)
(iOS 13+) to create a key command. - Input: A string representing the key (e.g.,
"s"
,UIKeyCommand.inputEscape
for special keys like Escape). - Modifier Flags: Combine flags like
.command
,.shift
,.alternate
, or.control
. - Discoverability: Set
discoverabilityTitle
(iOS 13+) for user-friendly names in the Command key overlay. - Responder Chain: Key commands are processed through the responder chain, so they must be added to a responder (e.g.,
UIViewController
orUIView
).
Advanced Features
Dynamic Key Commands
Dynamically adjust key commands by overriding keyCommands
:
override var keyCommands: [UIKeyCommand]? {
var commands = [UIKeyCommand]()
if canSave {
commands.append(UIKeyCommand(input: "s", modifierFlags: .command, action: #selector(saveAction), discoverabilityTitle: "Save"))
}
if canUndo {
commands.append(UIKeyCommand(input: "z", modifierFlags: .command, action: #selector(undoAction), discoverabilityTitle: "Undo"))
}
return commands
}
Special Keys
Use predefined inputs for special keys (iOS 9+):
UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(moveUp), discoverabilityTitle: "Move Up")
Enabling/Disabling
Control whether a key command is active by implementing canPerformAction(_:withSender:)
:
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(saveAction) {
return canSave // Only enable if saving is possible
}
return super.canPerformAction(action, withSender: sender)
}
Command Groups (iOS 15+)
Organize key commands into groups using UICommand
and UIMenu
for better discoverability:
override var keyCommands: [UIKeyCommand]? {
let saveCommand = UIKeyCommand(title: "Save", action: #selector(saveAction), input: "s", modifierFlags: .command)
let editMenu = UIMenu(title: "Edit", children: [saveCommand])
return [saveCommand]
}
Alternate Commands (iOS 13+)
Support alternate key combinations for the same action using UIKeyCommand.alternates
:
let command = UIKeyCommand(title: "Save", action: #selector(saveAction), input: "s", modifierFlags: .command, alternates: [
UIKeyCommand.Alternate(input: "s", modifierFlags: [.command, .shift], discoverabilityTitle: "Save As")
])
Best Practices
- User Discoverability: Always provide
discoverabilityTitle
for clarity in the Command key overlay. - Minimal Modifiers: Use simple key combinations (e.g., Command + key) to avoid complexity.
- Responder Chain: Ensure the responder implementing
keyCommands
is active in the chain (e.g., view controller is presented). - Accessibility: Test shortcuts with VoiceOver to ensure compatibility.
- Consistency: Follow macOS and iOS convention (e.g., Command + S for save, Command + Z for undo).
Limitations
- Hardware Dependency: Requires an external keyboard or software keyboard with Command key support (e.g., iPad).
- Responder Chain: Commands are ignored if the responder is not in the active chain.
- Discoverability: The Command key overlay is only available on iOS 13+ and requires user interaction to reveal.
- Complexity: Managing multiple commands or alternates can increase code complexity.
Summary
UIKeyCommand
enhances iOS apps by adding keyboard shortcut support, improving productivity and accessibility for users with external keyboards. It integrates seamlessly with UIKit’s responder chain and offers features like discoverability titles, dynamic commands, and menu organization (iOS 15+). By following best practices, developers can create intuitive and efficient keyboard-driven experiences.