How do you support hardware keyboards, shortcuts, menus and the pointer on iPad?
Predict first
Does a key command created with the command modifier report it?
import UIKit
let k = UIKeyCommand(title: "Save", action: #selector(UIResponder.becomeFirstResponder), input: "s", modifierFlags: .command)
print(k.modifierFlags.contains(.command), k.input ?? "")
- true s
- false s
Mental model. A good iPad app is a kitchen that works for a left-handed cook, a right-handed cook and a cook with a foot pedal: every task has more than one way in.
Make every action reachable beyond a tap. Keyboard shortcuts come from UIKeyCommand: declare an input and modifierFlags (such as .command) and an action, and the system shows it in the shortcut overlay when the user holds Command. Commands are found by walking the responder chain, so they belong on the controller or view that owns the action. Better is the menu system (UIMenuBuilder and UICommand): one declaration produces the menu bar on iPad and Mac Catalyst, the shortcut and the context menu, and items enable or disable by canPerformAction as the responder chain changes.
The pointer is the second input: add UIPointerInteraction to controls so the cursor morphs over them (the default for buttons), provide hover effects for custom views, and use UIContextMenuInteraction for secondary click and long press. Drag and drop uses UIDragInteraction and UIDropInteraction (or the collection view’s built-in delegates) to move items within and between apps. Text input already handles most keys; custom views that need raw key events override pressesBegan and become first responder. Test with a keyboard and a trackpad attached, with VoiceOver and with Full Keyboard Access, since those paths often expose actions only reachable by touch.
A key command is a plain description: an input string, modifier flags and an action. Dispatch happens through the responder chain.
Common traps
- Binding actions only to taps. Keyboard, pointer and accessibility users cannot reach them.
- Putting a key command on a view that is not in the responder chain. It never fires; attach it where the first responder can reach it.
They might follow up with
- Why prefer the menu system to bare key commands? One definition gives the menu bar, shortcuts and context menus, with automatic enabling.
- How does the system know which action to run? It sends the action up the responder chain from the first responder.
Related questions
- 7.1.2 What is the responder chain, and what is the first responder for?
- 7.1.3 How do gesture recognisers interact with touches and with each other?
- 7.8.2 How do you handle Apple Pencil input, and how does multitasking change your layout assumptions?
How do you handle Apple Pencil input, and how does multitasking… →