Skip to content

Instantly share code, notes, and snippets.

@douglashill
Last active December 13, 2019 21:54
Show Gist options
  • Save douglashill/e9e2876f755271ff3ac323c3f02da092 to your computer and use it in GitHub Desktop.
Save douglashill/e9e2876f755271ff3ac323c3f02da092 to your computer and use it in GitHub Desktop.
A UITabBarController subclass that allows navigating between tabs using cmd+number on a hardware keyboard.
// Douglas Hill, May 2019
// Find the latest version of this file at https://github.com/douglashill/KeyboardKit
import UIKit
/// A tab bar controller that allows navigating between tabs using cmd+number on a hardware keyboard.
/// So cmd+1 for the first tab, cmd+2 for the second tab etc.
public class KeyboardTabBarController: UITabBarController {
public override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
if let items = tabBar.items {
commands += items.enumerated().map { index, tabBarItem in
UIKeyCommand(maybeTitle: tabBarItem.title, action: #selector(scrollToNumberedTab), input: String(index + 1), modifierFlags: .command)
}
}
return commands
}
// For using command-1 to command-9.
@objc private func scrollToNumberedTab(_ sender: UIKeyCommand) {
guard let keyInput = sender.input, let targetTabNumber = Int(keyInput), targetTabNumber > 0 else {
return
}
selectedIndex = targetTabNumber - 1
}
}
private extension UIKeyCommand {
/// Makes the title optional compared to the UIKit method.
convenience init(maybeTitle: String?, action: Selector, input: String, modifierFlags: UIKeyModifierFlags) {
if let title = maybeTitle {
if #available(iOS 13, *) {
self.init(title: title, action: action, input: input, modifierFlags: modifierFlags)
} else {
self.init(input: input, modifierFlags: modifierFlags, action: action, discoverabilityTitle: title)
}
} else {
self.init(input: input, modifierFlags: modifierFlags, action: action)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment