Detect key press on virtual keyboard

后端 未结 3 1529
别那么骄傲
别那么骄傲 2020-12-20 10:05

I am working on a small children\'s game for my son that involves timing on the virtual keyboard.

Is possible to detect when a key on the virtual keyboard is presse

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 10:19

    It's not possible to get the touch events directly from the virtual keyboard. However, you could use a UITextField that you place offscreen, so that it's not visible and call becomeFirstResponder to show the keyboard. Then, as Khomsan suggested, you could implement the delegate method textView:shouldChangeTextInRange: to be notified whenever a key is pressed.

    A cleaner possibility would be to write a custom UIControl that implements the UIKeyInput protocol. You would only need to provide implementations for insertText:, deleteBackward and hasText (for this one, you can simply always return YES). To make the keyboard visible, you would again have to call becomeFirstResponder for your custom control.

    Both of these methods have in common that you only will be notified when the key is released (so that text is entered), not when the touch actually begins. As I said, it's not possible to get the tochesBegan event directly. If you need that, you would probably have to implement your own onscreen keyboard.

提交回复
热议问题