UITextFields in UITableView, entered values reappearing in other cells

后端 未结 2 669
借酒劲吻你
借酒劲吻你 2021-01-13 08:49

I have a UITableView with about 20 cells, in each cell there are three UITextFields. I did NOT subclass UITableViewCell, but when setting up each cell I set the textfields t

2条回答
  •  伪装坚强ぢ
    2021-01-13 09:23

    The issue is that when the cell is reused (i.e. dequeueReusableCellWithIdentifier returns non-nil), the cell is returned with the existing UITextView. To maintain the uniqueness of the tags, it'll be better to remove any previous UITextField:

    - (void)removeExistingTextSubviews:(UITableViewCell *)cell
    {
        NSMutableArray *toRemove = [NSMutableArray array];
        // I don't know if you have non-TextField subviews
        for (id view in [cell subviews]) {
            if ([view isKindOfClass:[UITextField class]] && view.tag >= 1000) {
               [toRemove insert:view];
            }
        }
    
        for (id view in toRemove) {
            [toRemove removeFromSuperView];
        }
    }
    
    ...
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    } else {
        [self removeExistingTextSubviews:cell];
    }
    //Modify cell, adding textfield with row-unique index value
    cell = [self modifyCellForHoleInfo:cell atIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone; 
    
    // Load value for textfield stored in dataArray
    ((UITextField *)[cell viewWithTag:1000+indexPath.row]).text = [dataArray objectAtIndex:indexPath.row];
    

    Please note that I haven't compiled the code, but it should serve as a starting point.

提交回复
热议问题