今日使ったので書く.これから数日は今回のアプリでやったことを小出しにできそう.
使い方
SwiftUIでキーボードショートカットを追加したいときはkeyboardShortcut(_ key: KeyEquivalent, modifiers: EventModifiers = .command)というmodifierを使う.
例えばスペースキーでなにかしたいときはこのようにすればいい.
Button {
// do something
} label: {
Text("Button")
}
.keyboardShortcut(.space, modifiers: [])
command + ctrl + aでならこう.
Button {
// do something
} label: {
Text("Button")
}
.keyboardShortcut("a", modifiers: [.command, .control])
注意点
一つ注意点があって,modifiersのデフォルト引数は.commandなので.keyboardShortcut(.space)とするとcommand + Spaceが登録される.
ちなみに
ちなみに,keyboardShortcut(_ shortcut: KeyboardShortcut)もあってそちらを使うこともできる.KeyboardShortcutにはcancelActionとdefaultActionという型プロパティが定義されている.
let cancelAction = KeyboardShortcut.cancelAction print(cancelAction.key, cancelAction.modifiers) // \u{1B}はエスケープキー // KeyEquivalent(character: "\u{1B}") EventModifiers(rawValue: 0) let defaultAction = KeyboardShortcut.defaultAction print(defaultAction.key, defaultAction.modifiers) // KeyEquivalent(character: "\r") EventModifiers(rawValue: 0)
雑記
ところで,グローバルなショートカットを追加できなくて諦めてたんだけどkeyboardShortcutのドキュメントを読んでたらmodified control(今回で言うButton)がメニューバーにあればそのアクションが実行できるという記述を見つけたので明日やる.