0

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 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! And it's true, you apparently don't need UITextFieldDelegate for this. Thank you!
2

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

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.