0

I am creating two TextFields dynamically and adding them the EditingChanged event like in the following example

import UIKit

var view:UIView = UIView()

let inp1:UITextField = UITextField(frame: CGRect(x: 20, y: 0, width: 100, height: 44))

inp1.addTarget(view, action:  "text_updated", forControlEvents: UIControlEvents.EditingChanged)

let inp2:UITextField = UITextField(frame: CGRect(x: 20, y: 50, width: 100, height: 44))

inp2.addTarget(view, action:  "text_updated", forControlEvents: UIControlEvents.EditingChanged)


view.addSubview(inp1)
view.addSubview(inp2)

func text_updated(){
    println("who has called me?")
}

As it is there is no way to know which one of the controls has called the text_updated function.

When I pass the TextField as a parameter

func text_updated(sender: UITextField) {

}

I get an "unrecognized selector sent to instance" exception.

How is it possible to know which TextField was changed?

abinop
  • 3,153
  • 5
  • 32
  • 46

1 Answers1

3

The difference between text_updated and text_updated: is subtle and it's quite easy to forget the colon.

If you want to call func text_updated(sender: UITextField) (method with at least one parameter), you have to set your textField target selector to "text_updated:", just like this:

inp2.addTarget(view, action:  "text_updated:", forControlEvents: UIControlEvents.EditingChanged)

In fact, when you're dealing with selectors, the rule is simple (from this Stack Overflow answer):

The colon is needed after the method's name if and only if the method takes an argument.

Community
  • 1
  • 1
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218