How do you make a button respond to an external keyboard key press?

I've got a set of buttons within a SwiftUI View which represent various letters of the alphabet. How can I make the buttons or the view accept external keyboard input, say from an iPad Pro's keyboard, so that instead of having to touch the screen a user with a keyboard can press a key? There's plenty of docs on this for the non-SwiftUI world, but I'm specifically wondering what's the recommended way of doing this in SwiftUI?


Thanks!

Replies

Just an idea I would need to explore more (if time).


Is the keyboard attached to a textField ?


If so, did you try to implement in shouldChangeCharactersIn delegate func


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

     guard value = aStr.first?.asciiValue else { return false }
     let valueForA = 65


     let valueFora = 97
     switch string:
          case "A"... "Z": // some action, based on [value - valueForA])
          case "a"... "z": // some action, based on[value - valueFora])
          default: return false
     }
     return true
}


I probably should have provided example code. Suppose I have a SwiftUI View like this:


struct MyView: View {
     var body: some View {
          Button(action: {
               print("A")
          }) {
               Text("A")
          }

          Button(action: {
               print("B")
          }) {
               Text("B")
          }
     }
}


This accepts touches on A and B presented on the screen and causes the associated action closures to run. How would I accept an external physical keyboard press of A or B to cause the code in the closures to run?

OK.


Those are 2 different system patterns:

- on screen, you tap a button

- on external keyboard, you enter data in a textField


So the point is to intercept those events (typing in a TextField), detect which letter pressed and then trigger the correct action.


May have a look at this discussion about onCommand

https://forums.developer.apple.com/thread/121018

I suspect that defining a UIKeyCommand and using .addKeyCommand(_:) to add it to your root controller would be part of this. Then you'd hopefully be able to use .onCommand{} via SwiftUI to register a block to handle the Selector you used when creating the UIKeyCommand instance.


I'll have to see if I can determine how this should work.

Darn. .onCommand{} isn't available on iOS. Le sigh. Looks like a custom solution is required after all.