Yes, it is possible to detect keyboard key press on iPhones without relying on the TextField string value in SwiftUI. One way to achieve this is by using the UIResponder method keyCommands()
to create a custom key command that gets triggered when a certain key is pressed on the keyboard. Here's an example:
struct ContentView: View {
var body: some View {
Text("Press the 'a' key")
.padding()
.background(Color.yellow)
.onKeyCommand("a") {
print("You pressed the 'a' key")
}
}
}
extension View {
func onKeyCommand(_ input: String, modifierFlags flags: UIKeyModifierFlags = [], action: @escaping () -> Void) -> some View {
return self.background(
KeyCommandReceiver(input: input, modifierFlags: flags, action: action)
)
}
}
struct KeyCommandReceiver: UIViewRepresentable {
let input: String
let modifierFlags: UIKeyModifierFlags
let action: () -> Void
func makeUIView(context: Context) -> UIView {
let view = UIView()
view.addKeyCommand(.init(input: input, modifierFlags: modifierFlags, action: #selector(handleKeyCommand)))
return view
}
func updateUIView(_ uiView: UIView, context: Context) {}
@objc private func handleKeyCommand() {
action()
}
}
In this example, we create a custom onKeyCommand
modifier that takes an input string (in this case, "a"), a set of modifier flags (such as command or shift), and a closure that gets executed when the key is pressed. We then create a custom KeyCommandReceiver
view that adds a new key command to its view's key commands array, and calls the action closure when the key is pressed.
We can use this modifier on any SwiftUI view, and specify the key we want to listen for as a string input. When the key is pressed on the keyboard, our custom action closure will get executed.
Asked: 2021-10-29 11:00:00 +0000
Seen: 10 times
Last updated: Dec 05 '22