I have a UIButton
and a UITextField
,when the button is pressed the textfield\'s content string will be equal to: This is a test string
Here is a Swift3 version of akashivskyy's answer:
func startObservingTextView() {
textView.addObserver(self, forKeyPath:"text", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
}
func stopObservingTextView() {
textView.removeObserver(self, forKeyPath: "text")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let textViewObject = object as? UITextView, textViewObject == textView, keyPath == "text" {
// text has changed
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//You code here...
}
Did u try this?
Maybe simple key-value observing will work?
[textField addObserver:self forKeyPath:@"text" options:0 context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if([keyPath isEqualToString:@"text"] && object == textField) {
// text has changed
}
}
Edit: I just checked it, and it works for me.
You can handle text change within UIControlEventEditingChanged
event. So when you change text programmaticaly just send this event:
textField.text = @"This is a test string";
[textField sendActionsForControlEvents:UIControlEventEditingChanged];
The delegate method may actually work for you. You get the text field, the range that will change, and the new string. You can put these together to determine the proposed string.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSMutableString *proposed = [NSMutableString stringWithString:textField.text];
[proposed replaceCharactersInRange:range withString:string];
NSLog(@"%@", proposed);
// Do stuff.
return YES; // Or NO. Whatever. It's your function.
}
You can add the UITextFieldTextDidChangeNotification
:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldChanged:)
name:UITextFieldTextDidChangeNotification
object:textField];
textField
(param object) is your UITextField.
selector
is your method that will be called when this notification was fired.