Search code examples
iosobjective-cuitableviewreuseidentifier

UITableview - Setting a property for cell is messed up with reused cells


I have a UITableView which act as a form. It has about 20 cells (with static content but dynamic cells). So I had an array with the fields and loading it in the table view. At some time the user will press the "Submit" button and I need all the textfields values that entered in the tableview's cells. So I created a @property for each textfield in each cell and I am assigning it in the cellForRowAtIndexPath:.

 if (indexPath.row==RPCVehicleType || indexPath.row==RPCExcess || indexPath.row==RPCDrivers){

    static NSString *tableIdentifier = @"TextFieldArrowCell";

    TextFieldArrowCell *cell = (TextFieldArrowCell*)[tableView dequeueReusableCellWithIdentifier:tableIdentifier];

    if (cell == nil) {
        cell = [[TextFieldArrowCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];
    }

    switch (indexPath.row) {
        case RPCVehicleType:
            self.typeOfVehicleTextfield = cell.valueField;
            break;
        case RPCExcess:
            self.excessTextfield = cell.valueField;
            break;
        case RPCDrivers:
            self.driversTextfield = cell.valueField;
            break;
        default:
            break;
    }

    return cell;

The problem with this code is that when I scroll to the bottom the cells are being reused and the properties are messed. So when I do [self.excessTextField setText:@"123"] the first time it's ok but after scrolling and execute again I can see other textfields of the same type of cell to change to that value. Any workaround to solve this issue?

Update: Tried this approach with the same result:

-(UITextField*)getTextFieldForRow:(NSInteger)row{

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
TextFieldArrowCell *cell = [self.tableV cellForRowAtIndexPath:indexPath];

return cell.valueField;

}


Solution

  • You can only retrieve data from visible cells (invisible cells don't exists or they have inappropriate data).

    There are several ways to do it. For you, the best solution would be to delegate (UITextFieldDelegate). You can obtain information about changes in UITextField, so you can update your data model.

    In tableView:cellForRowAtIndexPath: you pass correct (actual) data to table cell (this part of code you already have).