How can I detect a KeyPress event in a UITextField?

UITextView has a Modified event to handle a keystroke. However, UITextField does not have such an event.

How can I detect a KeyPress event in a UITextField ?

There is a method described here using notifications, but the problem with me is that I can’t unsubscribe from TextFieldTextDidChangeNotification.

+6
source share
4 answers

I'm not sure what your question is. The first thing you seem to have answered yourself, i.e. the solution (from your link) is to use NSNotificationCenter.DefaultCenter.AddObserver .

The second is unsubscribing - if you want to stop monitoring, you must call the previous method, i.e. NSNotificationCenter.DefaultCenter.RemoveObserver .

Just return the object returned from AddObserver so you can provide it to RemoveObserver .

note: If I didn’t understand your question correctly, use change and add some details and / or code of what you want to achieve, and we will do our best to help :-)

+3
source

As colinta suggested do it

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSLog(@"range = %@, replacement = %@, text = %@", NSStringFromRange(range), string, text); return YES; } 

and

 - (BOOL)textFieldShouldClear:(UITextField *)textField { NSLog(@"clear text"); return YES; } 

It will also work if the entry has been changed using spelling suggestions.

+2
source

Look at UITextFieldDelegate

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

Implement this protocol. It has callback methods for all text field changes.

+1
source

The cleanest way to observe UITextField changes is

 _textField.AddTarget((sender, e) => { // Do your stuff in here }, UIControlEvent.EditingChanged); 

You do not need to subscribe to the system-wide notification center, and you do not need to unregister the observer when the text field is destroyed.

Hope this helps someone in the future :)

0
source

Source: https://habr.com/ru/post/900981/


All Articles