AtWork AtWork - 4 months ago 29
iOS Question

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!!

Answer

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

In case of UITextField

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

In Case of UITextView :

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

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 make your code in method

- (void) textFieldText:(id)notification {
       Your_Code_Here }

UITextView

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

then you can make your code in method

- (void) textViewText:(id)notification {
       Your_Code_Here }

Hope it helps .

Comments