今日使ったので書く.これから数日は今回のアプリでやったことを小出しにできそう.
使い方
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
)がメニューバーにあればそのアクションが実行できるという記述を見つけたので明日やる.