0
votes

I have an app that I'd like the users are able to customize specific functuins to bluetooth keyboard keys in the app. I set up a view where they can tap a TextField next to a specific feature, then press a key on their remote (bluetooth keyboard) and it inserts that key into the TextField. They key buttons are stored as @Published var's in the Global Environment. I was trying to trigger actions via the .keyboardShortcut modifier, but it doesn't seem to be working (despite being able to compile)...here is a sample of a key in my Global Environment:

@Published var ksTrigger = "c" {
        didSet {
            if ksTrigger.count > 1 {
                ksTrigger = String(ksTrigger.prefix(1))
                UINotificationFeedbackGenerator().notificationOccurred(.error)
            }
            UserDefaults.standard.set(ksTrigger, forKey: K.Settings.KeyboardShortcuts.ksTrigger)
        }
    }

Here is the key in use in a button struct:

     Button("") {
                    env.toggleTrigger.toggle()
print("c key pressed")
             }
            .keyboardShortcut(KeyboardShortcut(KeyEquivalent(Character(env.ksTrigger))))

This button is in my main view, as a view in the back of my ZStack...However, when i have my keyboard connected and try pressing the "c" key, nothing happens...it just doesn't respond...I know there are some ways to use a UIViewRepresentable to detect key presses, but it's a bit over my head. Any ideas of a simpler way to make it work and run a block of code when a key is pressed in a view?

UPDATE 12-15-20 - Trying some other things, this also isn't working:

.keyboardShortcut(KeyEquivalent(Character(env.ksTrigger)))

Neither is this, just to test if a string can be identified as a character...pressing q on the keyboard doesn't print anything...i can see the QB button and tap it and it prints, but pressing q on my bt keyboard (with any modifiers held down) doesn't get the print statement to run...

Button(action: {
                print("q button pressed")
            }) {
                    Text("QB")
            }.keyboardShortcut("q", modifiers: .all)
1
The keyboardShortcut introduces handing of shortcuts like Modifier+Key, by default modifier is .command, so you added shortcut for ⌘+cAsperi
Is there a way to specify that there is no modifier? Do I need to manually set something like modifier: .none ?Benjamin B.

1 Answers

0
votes

I found another post that helped make this simple...I wish the .keyboardShortcut modifier did this, but apparently you need to use a responder and link said responder in your SceneDelegate file:

SwiftUI iOS - how to capture hardware key events