UITextField Value Changed Event?

IphoneUitextfield

Iphone Problem Overview


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

Iphone Solutions


Solution 1 - Iphone

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

Solution 2 - Iphone

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

Solution 3 - Iphone

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
}

Solution 4 - Iphone

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")
}

Solution 5 - Iphone

For swift this comes handy -

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristian StewartView Question on Stackoverflow
Solution 1 - IphonekovpasView Answer on Stackoverflow
Solution 2 - IphoneDmitry ShevchenkoView Answer on Stackoverflow
Solution 3 - IphonePaulsView Answer on Stackoverflow
Solution 4 - IphonewsnjyView Answer on Stackoverflow
Solution 5 - IphoneVivek BansalView Answer on Stackoverflow