簡體   English   中英

如何在UITextField中檢測KeyPress事件?

[英]How can I detect a KeyPress event in UITextField?

UITextView有一個Changed事件來處理按鍵。 但是, UITextField沒有此類事件。

如何在UITextField檢測KeyPress事件?

有描述的方法在這里使用的通知,但我的問題是,我無法從TextFieldTextDidChangeNotification退訂。

我不確定這是你的問題。 您似乎已經回答了第一個問題,即解決方案(來自您的鏈接)是使用NSNotificationCenter.DefaultCenter.AddObserver

第二個是關於取消訂閱的信息 -如果要停止觀察,則應調用先前的方法副本,即NSNotificationCenter.DefaultCenter.RemoveObserver

只需保留從AddObserver返回的對象,即可將其提供給RemoveObserver

注意:如果我無法正確理解您的問題,請使用編輯並添加一些您想要實現的細節和/或代碼,我們將盡力為您提供幫助:-)

正如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;
}

如果通過拼寫建議更改了輸入,它也將起作用。

看一下UITextFieldDelegate

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

實施該協議。 它具有用於所有文本字段更改的回調方法。

觀察UITextField更改的最干凈方法是

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

在銷毀文本字段時,您不必訂閱系統范圍的通知中心,也不必注銷觀察者。

希望這會對以后的人有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM