Search code examples
iosswiftkeyboardmac-catalyst

Detecting physical keyboard keypress in a catalyst program


I have a small iOS app that I wanted to compile for macOS with Catalyst. The app is working properly on the Mac, but it's a calculator app, so I wanted to be able to enter the numbers with the keyboard in addition to clicking on the buttons.

I searched and found that the override of pressesBegan was the good way to do it. But if I implement Apple's example at https://developer.apple.com/documentation/uikit/mac_catalyst/handling_key_presses_made_on_a_physical_keyboard?changes=_8 like this

    override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
        // Run backward or forward when the user presses a left or right arrow key.

        var didHandleEvent = false
        for press in presses {
            guard let key = press.key else { continue }
            if key.charactersIgnoringModifiers == UIKeyCommand.inputLeftArrow {
                //runBackward()
                didHandleEvent = true
            }
            if key.charactersIgnoringModifiers == UIKeyCommand.inputRightArrow {
                //runForward()
                didHandleEvent = true
            }
        }

        if didHandleEvent == false {
            // Didn't handle this key press, so pass the event to the next responder.
            super.pressesBegan(presses, with: event)
        }
    }

in my Appdelegate class, I've got an error for the instruction key = press.key:

Value of type 'UIPress' has no member 'key'

Reading the documentation of the class UIPress, I don't see any key member in XCode documentation (UIKit>Touches, Presses and Gesture>UIPress), but I see it on https://developer.apple.com/documentation/uikit/uipress ??

I didn't find any report of the message "Value of type 'UIPress' has no member 'key'" on Internet


Solution

  • I figured out my problem.

    I had an old version of XCode (11.3.1) which didn't know UIPress.key.

    After upgrading to XCode 11.4.1, all is OK.

    I don't really understand the reason, because I can compile the code for iOS 12.4, before the availability of the property key (Apple's documentation claims iOS 13.4+). But it works now !