Christian Stewart
Christian Stewart

Reputation: 15519

UITextField Value Changed Event?

How can I make it so that when the contents of a text field changes, a function is called?

Upvotes: 56

Views: 42599

Answers (5)

kovpas
kovpas

Reputation: 9593

Objective-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) {...}

Upvotes: 138

wsnjy
wsnjy

Reputation: 174

this is my solution.

Swift 4

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

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

Upvotes: 3

Vivek Bansal
Vivek Bansal

Reputation: 1326

For swift this comes handy -

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

Upvotes: 2

Pauls
Pauls

Reputation: 2636

I resolved the issue changing the behavior of shouldChangeChractersInRange. If you return NO the changes won't be applied by iOS internally, instead you have the opportunity to change it manually and perform any actions after the changes.

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

Upvotes: 8

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 32434

Actually, there is no value changed event for UITextField, use UIControlEventEditingChanged

Upvotes: 26

Related Questions