Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Adding Target/Action for UITextField Inside Custom UITableViewCell

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.

like image 609
Mitch Satchwell Avatar asked Sep 01 '26 00:09

Mitch Satchwell


1 Answers

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;
like image 181
Mutawe Avatar answered Sep 05 '26 06:09

Mutawe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!