Detecting UITextField content changes

2.3k views Asked by At

My app keeps crashing when the user types something into a textfield, displaying "NSInvalidArgumentException" and "unrecognized selector sent to instance ...". I am trying to detect when the user does type something, in order to then run some code. I've looked around here on Stackoverflow regarding this, and the code below is the result of my finds.

viewDidLoad()

adminPinField.delegate = self
adminPinField.addTarget(self, action:"pinChanged", forControlEvents:UIControlEvents.EditingChanged)

pinChanged method

func pinChanged(textField: UITextField) {
    //code
}

Class declaration

class ViewController: UIViewController, UITextFieldDelegate

Why am I getting this error and how do I fix it?

4

There are 4 answers

1
iDhaval On BEST ANSWER

you have to add : when you call method that contain parameter, change your method as below:

adminPinField.addTarget(self, action:"pinChanged:", forControlEvents:UIControlEvents.EditingChanged)

And you don't need to use UITextFieldDelegate for this.

0
Ilesh P On

I think u simply put the colon (:) behind the function name, and try like this

adminPinField.delegate = self
adminPinField.addTarget(self, action:"pinChanged:", forControlEvents:UIControlEvents.EditingChanged)

and methods write like that

func pinChanged(textField: UITextField) {
    //paste your code here
}

its helpful to you. Thanks

0
ares777 On

I think you action call should be

   adminPinField.addTarget(self, action:"pinChanged:", forControlEvents:UIControlEvents.EditingChanged)

Add the : This is also is available when call for example:

   mybutton.addTarget(self, action: "userbuttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
   func userbuttonClicked(sender:UIButton) { }
0
iAhmed On

Then in the textFieldDidChange: method you can examine the contents of the textField, and reload your contents as needed.

In Objective-c

[adminPinField addTarget:self 
          action:@selector(textFieldDidChange:) 
          forControlEvents:UIControlEventEditingChanged];

-(void)textFieldDidChange:(UITextField *)textField{

    NSLog (@"%@",adminPinField.text);
}

In Swift:

adminPinField.addTarget(self, action:"textFieldDidChange:", forControlEvents:UIControlEvents.EditingChanged)

This won't detect any change if contents are pasted inside the textfield. To detect that text change to do something like this:

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

Hope it helps