Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell with UITextField losing the ability to select UITableView row?

I am almost done implementing a UITableViewCell with a UITextField in it. Rather then going through CGRectMake and UITableViewCell.contentView I have implemented it the simpler way:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
    amountField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 190, 30)];
    amountField.placeholder = @"Enter amount";
    amountField.keyboardType = UIKeyboardTypeDecimalPad;
    amountField.textAlignment = UITextAlignmentRight;
    amountField.clearButtonMode = UITextFieldViewModeNever; 
    [amountField setDelegate:self];

    [[cell textLabel] setText:@"Amount"];
    [cell addSubview:amountField];
    return cell;
}

And then I also implemented the didSelectRow method, resigning the textField to allow showing the other fields input views.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    [amountField resignFirstResponder];
    ...
}

This works smoothly, only thing is there are other rows in the table, when those others are selected the entire cell is selected and turns Blue, while the one with my UITextField doesn't, I mean the field is selected and I can enter text but the cell is not selected. I have tested it and figured out the problem is in the line:

[cell addSubview:amountField];

It seems that this breaks the selectable cell behavior, and even adding it to [cell contentView] doesn't fix this. Did I miss something?

like image 527
Fabrizio Prosperi Avatar asked Jul 05 '11 08:07

Fabrizio Prosperi


1 Answers

If the text field has userInteractionEnabled set to YES, and it fills the entire cell, you can not get the cell to listen to touch. In order to get the cell to respond to touches, you need to set the userInteractionEnabled of the text field to NO.

Edit: And if you want to make the text field editable, when the cell is selected, add the following code in didSelectRowAtIndexPath: method,

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // get the reference to the text field
    [textField setUserInteractionEnabled:YES];
    [textField becomeFirstResponder];
}
like image 81
EmptyStack Avatar answered Nov 15 '22 03:11

EmptyStack