Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Keyboard key pressed in iphone?

I want to detect whenever the user presses any keyboard key.

Any method which is called only on typing any character and not when keyboard is shown.

Thanks!!

like image 612
AtWork Avatar asked Apr 15 '13 13:04

AtWork


People also ask

How do I know which key is pressed on my keyboard?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.

How do you show the pressed key on a Mac screen?

On your Mac, click the Input menu in the menu bar, then choose Show Keyboard Viewer. If the command isn't shown, choose Apple menu > System Preferences, click Keyboard , click Input Sources, then select “Show Input menu in menu bar.”


1 Answers

You can directly handle keyboard events every-time a user presses a key:

Swift

For Textfield use following delegate method -

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

}

For TextView use following delegate method -

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

}

Objective C

In case of UITextField

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

    // Do something here...
}

In Case of UITextView :

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

    // Do something here...
}

So every-time one of these method is called for each key you press using keyboard.

You can use NSNotificationCenter also. You only need do add any of these in ViewDidLoad method.

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

UITextField :

[notificationCenter addObserver:self
                       selector:@selector(textFieldText:)
                           name:UITextFieldTextDidChangeNotification
                         object:yourtextfield];

Then you can put your code in method textFieldText::

- (void)textFieldText:(id)notification {

    // Do something here...
}

UITextView

[notificationCenter addObserver:self
                       selector:@selector(textViewText:)
                           name:UITextViewTextDidChangeNotification
                         object:yourtextView];

Then you can put your code in method textViewText::

- (void)textViewText:(id)notification {

    // Do something here...
}

Hope it helps .

like image 139
Nishant Tyagi Avatar answered Oct 16 '22 18:10

Nishant Tyagi