如何在UITextField中检测到KeyPress事件?

时间:2011-11-07 23:47:03

标签: c# ios xamarin.ios uitextfield keypress

UITextView中,有一个已更改事件来处理按键。但是UITextField没有这样的事件。

如何在UITextField

中检测到KeyPress事件

有一种方法描述here使用通知,但我遇到的问题是我无法取消订阅TextFieldTextDidChangeNotification。

4 个答案:

答案 0 :(得分:3)

我不确定你的问题是什么。你似乎第一个回答了自己,即 解决方案(来自您的链接)是使用NSNotificationCenter.DefaultCenter.AddObserver

第二个是关于取消订阅 - 如果你想停止观察你应该调用前面的方法对应物,即NSNotificationCenter.DefaultCenter.RemoveObserver

只需保留从AddObserver返回的对象,即可将其提供给RemoveObserver

注意:如果我没有正确理解您的问题,请使用修改并添加一些您想要实现的细节和/或代码,我们将执行最好的帮助: - )

答案 1 :(得分:2)

正如colinta建议的那样,这样做

- (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;
}

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

如果通过拼写建议更改了输入,它也会起作用。

答案 2 :(得分:1)

查看UITextFieldDelegate

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

实施该协议。它具有所有文本字段更改的回调方法。

答案 3 :(得分:0)

观察UITextField更改的最简洁方法是

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

您不必订阅系统范围的通知中心,并且在您销毁文本字段时也不必取消注册观察者。

希望这将有助于未来的人:)

相关问题