views:

121

answers:

3

Hi guys. I have a few text fields and text views on my application's view. The keyboard comes up when I click in anyone of them. I have a method that gets called when any one of these objects is tapped in. However, I would like the method to execute its code only if the a certain Text Field(s) or a certain Text View(s) is tapped in. I would therefore like to have something like this in the method body:

{
   if(currentField != mySpecialField)
      {return;}

     //Rest of the method code...
}

Now, my question is, how do I get a reference to the currently tapped in field so that I can perform the if-check.

Thanks guys. I'm a total noobee in Objective-C. :(

+3  A: 

Controls that are subclasses of UIControl (for example UIButton or UITextField) automatically sends a reference to themselves along to their target.

When creating your text fields, just specify a selector that takes one argument. In this example, "myTextField" is an instance variable:

myTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[myTextField addTarget:self action:@selector(textFieldTapped:) forControlEvents:UIControlEventTouchUpInside];

And then the method we specified, textFieldTapped:, to handle the event:

- (void)textFieldTapped:(UITextField *)sender {
    // Ignore any events that doesn't come from myTextField
    if (sender != myTextField) return;

    // TODO: Do stuff
}

In the case of UITextField you can also check out the UITextFieldDelegate protocol (the "delegate" value of your text field). It sends out various events that can be used to register the same kind of things, for example:

- (void)textFieldDidBeginEditing:(UITextField *)textField
alleus
A: 
Unless the object is in the notification, you can't.
bbum
No, the `UIKeyboardDidHideNotification` and `UIKeyboardDidShowNotification` notifications does not supply any reference to the text field that is currently selected. You will need to either implement a control event target or a delegate as in my first answer. Another solution is to find out if a specific text field is selected by performing `isFirstResponder`. That method will return YES if the text field is selected, or NO if it's not.
alleus
A: 
bbum