Geesh_SO
Geesh_SO

Reputation: 2206

UITableViewCells reverting back to default or other values

enter image description here

So I've created a TableView as below, but I have quite an annoying problem.

When I come to this VC, I click Choose User, and I selected user Atoshum.

When I scroll down, this top cell goes off screen as I scroll through the bottom cells.

When I scroll back up, the cell has reverted to a default (or occasionally, takes the value of another cell).

I make the cells as such.

static NSString *CellIdentifier = @"Cell";

DMSDrugInstanceCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (!Cell) {
    Cell = [[DMSDrugInstanceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

Cell.chooseUserButton.tag = indexPath.row;

[Cell.chooseUserButton addTarget:self
                          action:@selector(performSegue:)
     forControlEvents:UIControlEventTouchUpInside];

return Cell;

Upvotes: 0

Views: 137

Answers (3)

Balram Tiwari
Balram Tiwari

Reputation: 5667

This is because the UITableView do not create the new cells for total number of elements. Rather it re-uses the cells which are off the visibility. Hence you feel that your data is reset or getting reflected on some other cell.

The best approach is to store all your data in some Array (let it be tagDataArray) and then set your cells as

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

DMSDrugInstanceCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[DMSDrugInstanceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
    Cell.chooseUserButton.tag = [tagDataArray objectAtIndex:indexPath.row];
    ...
    ...
    return Cell;
}

Upvotes: 1

Anand Mishra
Anand Mishra

Reputation: 1103

you are reusing table cell. So every time your cell reload then you need to set value in cell.

in cellForRowAtIndexPath method , you need to set value in cell according to index path.

Upvotes: 1

cpjolicoeur
cpjolicoeur

Reputation: 13106

In the cell creation you dont ever set any values. All you do is set the tag and then add an event target. If you want it to keep the choose, you need to store/save that choice when it is made and then in the cell create, set it based on that saved value.

Upvotes: 3

Related Questions