0

我创建了一个 UITableView,其中包含带有 2 个标签和 1 个 UIStepper 的单元格(动态)。这些标签之一与 UIStepper 的值同步。到目前为止,一切都很好。

当 UIStepper 的值发生变化时,这就是我的代码的样子:

- (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
}

在第一行按下 UIStepper的+后,可变数组mengen如下所示:

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

正是如此,我已经预料到了!

不仅第一行的标签menge设置为 1,第八行的标签也设置为 1。如果我在第二行按+,第二行和第九行的标签就会改变,依此类推。

为什么会这样?

更新:cellForRowAtIndexPath 方法

- (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;

}
4

2 回答 2

0

单元格正在出队并重用值。如果您希望单元格反映值,请使用将单元格 indexpath.row 映射到数组中的索引的数据源映射

于 2013-07-27T17:27:41.003 回答
0
- (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;

}
于 2013-07-27T17:40:51.070 回答