Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting the change of content of UITextField when the change is not made by the keyboard

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, how can I detect that this text field has changed its contents in this case?

p.s. UITextField's delegate methods do not work in such case

UPDATE: I want this behavior to be on iOS 6+ devices.

like image 274
JAHelia Avatar asked Dec 19 '12 12:12

JAHelia


People also ask

What is a UITextField?

An object that displays an editable text area in your interface.

How do I change a text field in Swift?

You can do this by holding Option and clicking on the file. It should open your Swift file side by side to your storyboard. Now select the UITextField in your storyboard that you want to monitor text changes too.

How do you dismiss a keyboard in Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.


3 Answers

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.

like image 154
Sebastian Avatar answered Oct 02 '22 14:10

Sebastian


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.

like image 40
akashivskyy Avatar answered Oct 02 '22 14:10

akashivskyy


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];
like image 43
Alexey Kozhevnikov Avatar answered Oct 02 '22 12:10

Alexey Kozhevnikov