How can I make it so that when the contents of a text field changes, a function is called?
Asked
Active
Viewed 4.2k times
5 Answers
138
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) {...}

kovpas
- 9,553
- 6
- 40
- 44
-
22Weird, based on UIControlEventDidEnd & UIControlEventDidBegin, one would assume that it was UIControlEventValueChanged... What exactly does UIControlEventValueChanged do then? – Jarrod Feb 22 '12 at 00:01
-
@kovpas if we change value programmatically then it didn't get call, any idea what to do ?. for example myTextField.text = "Krishna" – Krishna Sharma Jul 21 '20 at 17:37
26
Actually, there is no value changed event for UITextField
, use UIControlEventEditingChanged

Dmitry Shevchenko
- 31,814
- 10
- 56
- 62
8
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
}

Pauls
- 2,596
- 19
- 19
-
4Note that setting text property will move cursor to the end of text, which might affect editing – jarnoh Mar 04 '14 at 18:43
-
3
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")
}

wsnjy
- 174
- 1
- 7
2
For swift this comes handy -
textField.addTarget(self, action: #selector(onTextChange), forControlEvents: UIControlEvents.EditingChanged)

Vivek Bansal
- 1,301
- 13
- 21