Search code examples
iosswiftuitextfielduitextfielddelegate

Detecting UITextField content changes


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?


Solution

  • 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.