I've created a UITableView containing cells (dynamic) with 2 labels and 1 UIStepper. One of these labels get synced with the value the UIStepper. So far, so good.

This is what my code looks like, when the value of a UIStepper changes:

- (IBAction)stepper:(id)sender {
    UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    int row = indexPath.row;
    // I just determined in which row the user tapped the UIStepper.

    UIStepper *stepper = (UIStepper *)[cell viewWithTag:300];
    UILabel *menge = (UILabel *)[cell viewWithTag:100];
    int anzahl = stepper.value;
    menge.text = [NSString stringWithFormat:@"%i",anzahl];
    // and the label just got synced with the UIStepper value

    [_mengen insertObject:[NSString stringWithFormat:@"%i",anzahl] atIndex:row];
    // and the value got saved for further calculations
}

The mutable array mengen looks like this, after pressing the + of the UIStepper in the first row:

(
    1,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0
)

Exactly that, I've expected!

BUT not only the label menge in the first row was set to 1, also the label in the eighth row did. If I press the + in the second row, the labels in the second and in the ninth row change, and so on.

Why is this happening?

Update: cellForRowAtIndexPath method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    UILabel *artikel = (UILabel *)[cell viewWithTag:200];
    cell.selected = NO;
    [artikel setText:[_artikel objectAtIndex:[indexPath row]]];
    return cell;

}
有帮助吗?

解决方案

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    UILabel *artikel = (UILabel *)[cell viewWithTag:200];
    cell.selected = NO;
    [artikel setText:[_artikel objectAtIndex:[indexPath row]]];

    // Add this
    UILabel *menge = (UILabel *)[cell viewWithTag:100]; 
    // As cell may have been reused menge already many have some value. 
    // Initialize menge with an appropriate value
    menge.text = @"";

   return cell;

}

其他提示

The cell is dequeing and reusing values. If you want the cells to reflect the value, have a data source map that maps the cell indexpath.row to the index in the array

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top