iOS - Adding Target/Action for UITextField Inside Custom UITableViewCell

cocoa-touch, ios, objective-c, uikit, uitableview

Solution

Use `UITextField` `delegate` Methods:

UITextField delegate

//Use this method insted of addTarget:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if (textField == tf) {
        [self myMethod];
        return NO;
    }

  return YES;
}

and dont forget to set the delegate to the textField:

 tf.delegate = self;

Problem

I have `UITableView` which uses a custom `UITableViewCell` containing a `UITextField`. I want to call a method (`myMethod`) when it is clicked (`UIControlEventTouchDown`) and attempted to wire this up inside the `UITableView` delegate method `cellForRowAtIndexPath` by doing the following: ``` [tf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown]; ``` When the `UITextField` is clicked, nothing happens. I attempted to do the exact same thing for another `UITextField` outside of the `UITableView`: ``` [othertf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown]; ``` When I click on `othertf` the method is called as I would expect. I'm a bit confused as the code is identical apart from I've swapped `tf` for `othertf`. Below is the complete code for `cellForRowAtIndexPath`: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *DetailCellIdentifier = @"DetailFieldView"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DetailCellIdentifier]; if (cell == nil) { NSArray *cellObjects = [[NSBundle mainBundle] loadNibNamed:DetailCellIdentifier owner:self options:nil]; cell = (UITableViewCell*) [cellObjects objectAtIndex:0]; } cell.selectionStyle = UITableViewCellSelectionStyleNone; UITextField *tf = (UITextField *)[cell viewWithTag:2]; tf.text = @"some value"; [othertf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown]; [tf addTarget:self action:@selector(myMethod) forControlEvents:UIControlEventTouchDown]; return cell; } ``` Can anyone spot what I'm doing wrong? It's probably something simple as I am new to iOS development.

Original source