Detect key press on virtual keyboard

后端 未结 3 1527
别那么骄傲
别那么骄傲 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.

    0 讨论(0)
  • 2020-12-20 10:20

    For TextView you can use...

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    - (void)textViewDidChange:(UITextView *)textView
    

    For TextField you can use...

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    

    See UITextViewDelegate and UITextFieldDelegate on Apple website.

    0 讨论(0)
  • 2020-12-20 10:21

    Yes you can just use:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        //do what you need
        [super touchesBegan:touches withEvent:event];
    }
    
    0 讨论(0)
提交回复
热议问题