输入按键时获取 UITextField 的值?

假设我有以下代码:

IBOutlet UITextField* nameTextField;
IBOutlet UILabel* greetingLabel;

我希望用户一按下任何键,greetingLabel就读取“ Hello [ nameTextField ]”。

我所需要的基本上是 iPhone 版的 Cocoa 委托方法 controlTextDidChange

每次击键时调用 textField:shouldChangeCharactersInRange:委托方法:

- (BOOL)              textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string

字符串参数返回被按下的字符。但是实际的 textField值(nameTextField.text)仍然是空的。

我在这里遗漏了什么? (我希望 nameTextField反映用户到目前为止输入的确切字符串)。

67295 次浏览

you could register an action for the event UIControlEventEditingChanges on the text field:

[nameTextField addTarget:self action:@selector(updateLabelUsingContentsOfTextField:) forControlEvents:UIControlEventEditingChanged];

...

// TODO: error checking


- (void)updateLabelUsingContentsOfTextField:(id)sender {


greetingLabel.text = [NSString stringWithFormat:@"Hello %@", ((UITextField *)sender).text];


}

UITextField has a notification UITextFieldTextDidChange which will be fired every time the text changes if you register for it. Just register for that notification and in the method called by the notification, change the label's text.

To add to this, the object passed to your notification handler will have the text of the UITextField.

Hope that helps.

It turns out, the easiest way to do this is using Interface Builder:

  • Add a IBAction (to the ViewController, say, as in this case)
  • Ctrl-Click (or right click) on the UITextField in Interface Builder
  • Connect the "Editing Changed" event to the File's Owner's IBAction added in the first step.

Works like a charm :) (I can't believe I spent numerous days on this, and to realize now that the solution was much simpler than I'd thought :P)