滚动时UITableViewCell图像发生变化

我有一个标题和每个单元格上的图像的UITableView。 有些单元格会有一个默认的图像,其他的则不会。 当我滚动表时,某些行的图像不是预期的,而是显示另一行的图像而不是预期的图像。 如果我不使用dequeuereuseidentifier一切正常,但我想用它,因为我有很多细胞。

任何build议?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"]; CGRect titleRect = CGRectMake(60, 6, 200, 24); UILabel *title = [[UILabel alloc] initWithFrame: titleRect]; title.tag = 1; title.backgroundColor = [UIColor clearColor]; title.font = [UIFont fontWithName:@"AdelleBasic-Bold" size:15.5]; [cell.contentView addSubview:title]; UIImageView *defaultCellImage = [[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 42, 42)]; defaultCellImage.tag = 2; [defaultCellImage setImage:[UIImage imageNamed: @"Default_Row_Image"]]; [cell.contentView addSubview:defaultCellImage]; } NSUInteger row = [indexPath row]; Movie *movie = [_movies objectAtIndex: row]; UILabel *titleRowLabel = (UILabel *) [cell.contentView viewWithTag:1]; titleRowLabel.text = [movie title]; UIImageView *cellImage = (UIImageView *) [cell.contentView viewWithTag:2]; if (![movie.imageName isEqualToString:@""]) [cellImage setImage:[UIImage imageNamed: [movie imageName]]]; return cell; } 

在表格视图中使用的第一个单元格将被正确加载。 由于没有单元出队,因此if (cell == nil)将返回YES并且您的单元格将其图像设置为默认值。 然后,如果您稍后在方法中满足您设置不同图像的条件,则会显示不同的图像。 到现在为止还挺好。

但是,当一个可重用的单元格出队时,它已经有一个图像集,这可能不是默认的。 因为cell == nil现在将返回NO ,所以即使它是应该显示的图像,这个单元也不会将其图像重置为默认值。