Search code examples
uitableviewios7reusability

UITableViewCell Reusability


I have a simple tableView with 20 rows. I created a subclass custom UITableview cell, and in cellforRowAtIndex, I add a textfield to the cell once every other 3 rows. When I scroll up and down text fields show up in the wrong rows. Note, I can't make UItextfield part of my custom cell, because this can be anything, checkbox, radio button, but for simplicity I chose UITextfield... What am I doing wrong?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:   (NSIndexPath *)indexPath
  {
    static NSString *CellIdentifier = @"TestCellIdentifier";
    testCell *cell = (testCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(!cell)
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
else{

    //HMMM I also tried removing it before adding it- it doesn't work neither
    for(UIView *v in cell.subviews){
        if(v.tag == 999 ){
            [v removeFromSuperview];
        }
    }

   //add UItextField to row if it's divisible by 3 
    if(indexPath.row %3 ==0){

        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(400, 10, 300, 30)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.font = [UIFont systemFontOfSize:15];
        textField.placeholder = [NSString stringWithFormat:@"%d",indexPath.row];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDone;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        textField.tag = 999;

        [cell addSubview:textField];
    }
}


cell.textLabel.text = [NSString stringWithFormat:@"%d",indexPath.row];


return cell;
}

Solution

  • don't use the Reusability ? in this scene,i will not use the reusability