iOS 9 Swift Programming Cookbook (2015)
Chapter 3. The User Interface
3.10 Associating Keyboard Shortcuts with View Controllers
Problem
You want to allow your application to respond to complex key combinations that a user can press on an external keyboard, to give the user more ways to interact with your app.
Solution
Construct an instance of the UIKeyCommand class and add it to your view controllers using the addKeyCommand(_:) method. You can remove key commands with the removeKeyCommand(_:) method.
Discussion
Keyboard shortcuts are very useful for users with external keyboards. Why? Since you asked, it’s because they can use keyboard shortcuts. For instance, on a document editing iOS app, the user might expect to press Command+N to create a new document, whereas on an iOS device this may be achieved by the user pressing a button such as “New”.
Let’s say that we want to write a single-view app that allows users with an external keyboard to press Command+Alt+Control+N to see an alert controller. When our view is loaded, we will create the command and add it to our view controller:
override func viewDidLoad() {
super.viewDidLoad()
let command = UIKeyCommand(input: "N",
modifierFlags: .Command + .Alternate + .Control,
action: "handleCommand:")
addKeyCommand(command)
}
As you can see, I am using the + operator between items of type UIKeyModifierFlags. This operator by default does not exist, so let’s write a generic operator method that enables this functionality for us:
func +<T: OptionSetType where T.RawValue : SignedIntegerType>
(lhs: T, rhs: T) -> T{
return T(rawValue: lhs.rawValue | rhs.rawValue)
}
When the command is issued, iOS will attempt to call the method that we have specified. In there, let’s show the alert:
func handleCommand(cmd: UIKeyCommand){
let c = UIAlertController(title: "Shortcut pressed",
message: "You pressed the shortcut key", preferredStyle: .Alert)
c.addAction(UIAlertAction(title: "Ok!", style: .Destructive, handler: nil))
presentViewController(c, animated: true, completion: nil)
}
Open this in the simulator. from the Hardware menu, select Keyboard, and then select the Connect Hardware Keyboard menu item (see Figure 3-26). While the focus is on the simulator, press the aforementioned key combinations and see the results for yourself.
Figure 3-26. You can enable a hardware keyboard even in the simulator. This is necessary to test the output of this recipe.
See Also