UITextField值更改事件?

时间:2010-10-23 21:25:06

标签: iphone uitextfield

如何才能使文本字段的内容发生变化时,会调用一个函数?

5 个答案:

答案 0 :(得分:126)

<强>目标C

[myTextField addTarget:self 
                action:@selector(textFieldDidChange:) 
      forControlEvents:UIControlEventEditingChanged];

Swift 4

myTextField.addTarget(self, action: #selector(textFieldDidChange(sender:)), for: .editingChanged)

@objc func textFieldDidChange(sender: UITextField) {...}

答案 1 :(得分:20)

实际上,UITextField没有值更改事件,请使用UIControlEventEditingChanged

答案 2 :(得分:8)

我解决了改变shouldChangeChractersInRange行为的问题。如果您返回NO,iOS内部将不会应用更改,您可以手动更改它并在更改后执行任何操作。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //Replace the string manually in the textbox
    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //perform any logic here now that you are sure the textbox text has changed
    [self didChangeTextInTextField:textField];
    return NO; //this make iOS not to perform any action
}

答案 3 :(得分:1)

对于swift来说这很方便 -

textField.addTarget(self, action: #selector(onTextChange), forControlEvents: UIControlEvents.EditingChanged)

答案 4 :(得分:0)

这是我的解决方法。

快捷键4

textField.addTarget(self, action: #selector(self.textFieldDidChange(sender:)), for: .editingChanged)

@objc func textFieldDidChange(sender: UITextField){
   print("textFieldDidChange is called")
}