How can I detect a KeyPress event in UITextField?

前提是你 提交于 2019-12-10 12:59:08

问题


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.


回答1:


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 :-)




回答2:


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.




回答3:


Look at the UITextFieldDelegate

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

Implement that protocol. It has call back methods for all the text field changes.




回答4:


The cleanest way to observe UITextField changes is

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

You don't have to subscribe to a system-wide notification center and you don't have to unregister observer when you're destroing a text field.

Hope this will help someone in the future :)



来源:https://stackoverflow.com/questions/8044288/how-can-i-detect-a-keypress-event-in-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!