Tim W
Tim W

Reputation: 81

Erratic contents of UITextField as subviews of table cells when scrolling

I'm trying to add a UITextField as a subview to my table cells. The content of the text fields is fine until I start scrolling and the cells start to be reused. The images illustrate the problem.

first screenshot second screenshot third screenshot

At first, the blue values on the right in the UITextField are correct, i.e. the value corresponds to the row number. The second and third images, scrolled down and back up, show that the values are being reused in odd ways.

How do I avoid this? Using unique values for reuseIdentifier solves this problem, but obviously it's not very efficient.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITextField *numberTextField;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        numberTextField = [[UITextField alloc] initWithFrame:CGRectMake(200, 10, 95, 30)];
        numberTextField.adjustsFontSizeToFitWidth = YES;
        numberTextField.textColor = [UIColor blueColor];
        numberTextField.placeholder = @"Enter value";
        numberTextField.keyboardType = UIKeyboardTypeDecimalPad;
        numberTextField.tag = ([indexPath row]+1);
        numberTextField.backgroundColor = [cell backgroundColor];
        numberTextField.textAlignment = NSTextAlignmentRight;
        numberTextField.clearButtonMode = UITextFieldViewModeNever;
        numberTextField.clearsOnBeginEditing = YES;
        [numberTextField setEnabled:YES];

        [cell addSubview:numberTextField];

    } else {
        numberTextField = (UITextField *)[cell.contentView viewWithTag:([indexPath row]+1)];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"Row %i",[indexPath row]+1];
    numberTextField.text = [NSString stringWithFormat:@"Value: %i",[indexPath row]+1];

    return cell;
}

Upvotes: 0

Views: 218

Answers (1)

jsd
jsd

Reputation: 7703

The problem is you only assign the tag to the numberTextField when it is created. If it gets reused, it doesn't get its tag reassigned.

You should use a constant tag number for the UITextField instead of using row+1.

Upvotes: 1

Related Questions