Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...