Skip to main content

キーボードイベントを拾う

最小限テンプレ

swift
struct KeyboardTestView: View {
@FocusState private var isFocused: Bool

var body: some View {
VStack {
...
}
.focusable() // ★1. focus あてられるようにする
.focused($isFocused)
.onAppear {
isFocused = true // ★2. 表示時に focus あてる
}
.focusEffectDisabled(true) // ★3. 青い枠は無効化する(これはもっと親レイヤでやっても良いかも)
.onKeyPress { keyPress in // ★4. キーボードイベントを拾う(特定のキーに絞らない)
return handleKeyPress(keyPress)
}
.onKeyPress(.upArrow) { // 特定のキーを拾う場合は こうでも良い
..
return .handled
}
}

func handleKeyPress(_ kp: KeyPress) -> KeyPress.Result {
if kp.modifiers.contains(.shift) && kp.characters == "a" {
print("A")
}
/* これでも良さそう
if kp.modifiers.contains(.shift) && kp.key == KeyEquivalent("a") {
print("A")
}
*/
if kp.modifiers.isEmpty && kp.key == .rightArrow {
print("RightArrow")
}

return .handled // or .ignored
}
}