Check which Textfield is calling textFieldDidBeginEditing

Asked

Viewed 46 times

1

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

For example:

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

I can use the Outlet of each textField or there is another way to do this?

  • I do not know if there is a more efficient way than to create these conditions from the IBOutlet for each UITextField. Exactly as you described.

  • @Paulorodrigues, that’s right, I’ll do it that way.

1 answer

1


Yes, you can use Outlet to make this check.

Basically you would do that:

@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");
        }
    }

Taking into account both forms, it is possible to observe that through the Outlet the code becomes more readable.

Edit: As a complement to Luis, it is also possible to use constants to compare 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");
    }
}
  • 1

    One can create constants for each textField and use them in comparison to tag, so it would be clear in the same way that textField you are referring and do not need Outlets

  • Yes, there is also this possibility Luis, thanks for your complement! Only if he’s using the Outlet elsewhere, then it would complicate my opinion.

  • I agree, I find the way by directly comparing the object with the outlet the clearest, I even used it in a form and encased about 10 if/else because I couldn’t find a better way.

  • @Luishenrique when you have many "Else if" you can be sure that the switch is ideal for these cases. http://stackoverflow.com/a/35691147/2303865

Browser other questions tagged

You are not signed in. Login or sign up in order to post.