Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect a KeyPress event in UITextField?

In UITextView there is a Changed event to handle keypress. However the UITextField has not such event.

How can I detect a KeyPress event in UITextField?

There is a method described here using notifications, however the problem I have is that I cannot unsubscribe from the TextFieldTextDidChangeNotification.

like image 532
Yiannis Mpourkelis Avatar asked Nov 07 '11 23:11

Yiannis Mpourkelis


2 Answers

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

The second is about unsubscribing - if you want to stop observing you should call the previous method counterpart, i.e. NSNotificationCenter.DefaultCenter.RemoveObserver.

Just keep the object returned from AddObserver so you can supply it to RemoveObserver.

note: If I did not understand your question correctly please use edit and add some details and/or code of what you want to achieve and we'll do our best to help :-)

like image 198
poupou Avatar answered Nov 12 '22 17:11

poupou


As colinta suggested, do this

- (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 input was changed via spelling suggestions.

like image 36
Wei Avatar answered Nov 12 '22 18:11

Wei