Check which TextField is calling textFieldDidBeginEditing

1

I have several textFields on my screen and I would like to know which one started an action.

For example:

func textFieldDidBeginEditing(textField: UITextField) {
    if textField // aqui eu não sei comparar para ver qual textField iniciou essa chamada
}

Can I use the Outlet for each textField or is there another way to do this?

    
asked by anonymous 11.02.2016 / 16:52

1 answer

1

Yes, you can use the Outlet to do this check.

Basically you would do this:

@IBOutlet weak var text1: UITextField!
@IBOutlet weak var text2: UITextField!

func textFieldDidBeginEditing(textField: UITextField) {

 if textField == text1 {
    print("Text 1 mudou");
 } else if textField == text2 {
    print("Text 2 mudou");
 } else {
    print("outro text mudou");
 } 
}

Another way you can do this is by checking the UITextView tag. For example, taking into account that text1 has the tag '1' and text2 with the tag '2' the code would look like this:

 @IBOutlet weak var text1: UITextField!
 @IBOutlet weak var text2: UITextField!

     func textFieldDidBeginEditing(textField: UITextField) {

        if(textField.tag == 1) {
            print("Text 1 changed");
        } else if(textField.tag == 2) {
            print("Text 2 changed");
        } else {
            print("Text ?? changed");
        }
    }

Considering both forms, you can see that the code is more readable through the Outlet.

Edit: According to Luis's complement, it is also possible to use constants to perform the comparison of the tags, as in the example:

let kTextField1 = 1;
let kTextField2 = 2;

func textFieldDidBeginEditing(textField: UITextField) {

    if(textField.tag == kTextField1) {
        print("Text 1 changed");
    } else if(textField.tag == kTextField2) {
        print("Text 2 changed");
    } else {
        print("Text ?? changed");
    }
}
    
11.02.2016 / 17:21