0

我正在使用 if 语句,以便只有特定的单元格才能获取图像。在我的测试示例中,只有一个单元格应该获取图像,并且 if 语句只运行一次。if 语句还会更改标签的文本。标签已正确更改,但图像被添加到多个单元格中,尤其是当我上下滚动时。如何让它不向其他单元格添加额外的图像。

UIImageView *imageView= [[UIImageView alloc]initWithFrame:CGRectMake(114,5, 122, 63)];
    if (condition) {
    [imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Placeholder.png"]];
                imageView.tag = 777;
                [cell addSubview:imageView];
                cell.titleLabel.text = [dict valueForKey:@"name"];
                cell.titleDescription.text = [dict valueForKey:@"summary"];
    } else {
                [[cell viewWithTag:777] removeFromSuperview];
    }
4

2 回答 2

1

UITableViewCell 被缓存了,所以不要总是创建一个新的 UIImageView,而是先检查它是否有一个:

UIImageView * imageView = (UIImageView*)[cell viewWithTag:777];

if (condition) {

    if(!imageView) {
        imageView= [[UIImageView alloc]initWithFrame:CGRectMake(114,5, 122, 63)];
    }
    [imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Placeholder.png"]];
    imageView.tag = 777;
    [cell addSubview:imageView];
    cell.titleLabel.text = [dict valueForKey:@"name"];
    cell.titleDescription.text = [dict valueForKey:@"summary"];
} else {
    [imageView removeFromSuperview];
}

您可能会将多个 imageViews 添加到一个单元格,因此 removeFromSuperView 只是删除了第一个。

于 2013-07-23T09:45:59.547 回答
0

在创建单元格的过程中这样做

  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:  (NSIndexPath *)indexPath
 {
      UITableViewCell *cell = [aTableVIew dequeueReusableCellWithIdentifier:@"cell"];
      if(cell == nil)
      {
           cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]autorelease];
         UIImageView *aImgView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 0, 40, 40)];
       aImgView.tag = 777;
       [cell addSubview:aImgView];
       [aImgView release];
     }

     //use your condition hear onwards to make changes
    if(indexPath.section == 0)
     {
        UIImageView *view = (UIImageView *)[cell viewWithTag:777];
        view.image = [UIImage imageNamed:@"peter.png"];

     }
    else if (indexPath.section == 1)
     {
          if(indexPath.row == 0 )
           {      
              UIImageView *view = (UIImageView *)[cell viewWithTag:777];
              view.image = nil;
           }
          else
          {
              UIImageView *view = (UIImageView *)[cell viewWithTag:777];
              view.image = [UIImage imageNamed:@"peter.png"];

          }

    }

 return cell;

}


根据要求改变

注意:我没有使用 ARC

于 2013-07-23T09:47:13.513 回答