UITableview 通过滚动复制图像

UITableview duplicate Images by scrolling

我有以下行为:我有一个 table 行数 = 20

我已经使用 UIImage 在 Storyboard UITableView Cell 中创建了。 我使用函数 didSelectRowAtIndexPath 来显示和隐藏图像。如果我 select 一行,将显示 UIImage xxx.png。如果我再次 select 同一行,则图像将被隐藏。这很有效,但是当我向下滚动时,我看到带有图像的行,但我没有 selected 这一行。 当我 select 一行时我只会看到图像,而当我滚动 table.

时我不会看到重复的图像

这是我的代码:

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

WorkoutTableVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WorkoutCell" forIndexPath:indexPath];
cell.checkImage= nil;

    if (cell == nil)
    {
        cell = [[WorkoutTableVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WorkoutCell"];


    }

    else{
        //Old cell...get previously createdd imageview
        cell.checkImage = (UIImageView*)[cell.contentView viewWithTag:1001];
    }

long row = [indexPath row];   
cell.lblCell.text = _MyValues[row];
return cell;
  }

我希望你能理解我的问题,抱歉我的英语不好:(

单元格是重复使用的,所以每次都需要设置单元格的图片。您需要有另一个数据源,其中包含每个 indexPath 的图像,并使用它来为单元格中的 UIImageView 设置图像。

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

    WorkoutTableVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WorkoutCell" forIndexPath:indexPath];


    if (cell == nil)
    {
        cell = [[WorkoutTableVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WorkoutCell"];
    }

    long row = [indexPath row];   
    cell.lblCell.text = _MyValues[row];

    // set the image for the UIImageView here
    cell.imageView.image = _MyImages[row];

    return cell;
}

更好的方法是让您的数据源是一对 key/value(如 NSDictionary),键是标签中的文本,值是应该分配的图像到 UIImageView。