在UITableView-XMLparsing中混合了图像

编辑:其实图像显示正常,这是当我滚动,他们混在一起…

我正在parsing一个XML文件,并将其链接到我正在放入UITable的图像中。 出于某种原因,图片变得混乱起来,当我向下滚动桌子时,他们中的一些甚至开始改变! 这里是我用于我的UITable的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; Tweet *currentTweet = [[xmlParser tweets] objectAtIndex:indexPath.row]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; CGRect imageFrame = CGRectMake(2, 8, 40, 40); customImage = [[UIImageView alloc] initWithFrame:imageFrame]; [cell.contentView addSubview:customImage]; } NSString *picURL = [currentTweet pic]; if (![picURL hasPrefix:@"http:"]) { picURL = [@"http:" stringByAppendingString:picURL]; } customImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:picURL]]]; return cell; } 

任何想法我做错了什么? 任何帮助是认真的赞赏。 谢谢!

你的问题是,如果单元格不是nil (即,你已经成功地重用了一个已经滚动屏幕的单元格),你没有正确设置customImage指针(因为它是一个类实例variables,它的值从它创build的最后一个单元格)。 因此,为kCustomImageTag定义一个非零常量,然后修改cellForRowAtIndexPathif语句为:

 if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; CGRect imageFrame = CGRectMake(2, 8, 40, 40); customImage = [[UIImageView alloc] initWithFrame:imageFrame]; [cell.contentView addSubview:customImage]; customImage.tag = kCustomImageTag; } else { customImage = [cell.contentView viewWithTag:kCustomImageTag]; } 

在创buildcustomImage时设置tag ,并使用该tag检索重用的UITableViewCell的现有customImage

当你要求一个可重用的单元格,如果它不是零它是一个单元格,你已经分配,​​并添加子视图到它的contentView …你应该先删除所有的子视图cellForRow ..

 if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; CGRect imageFrame = CGRectMake(2, 8, 40, 40); customImage = [[UIImageView alloc] initWithFrame:imageFrame]; [cell.contentView addSubview:customImage]; } else { for (UIView *v in cell.contentView) [v removeFromSuperView]; } 

看看这个项目: https : //github.com/bharris47/LIFOOperationQueue

它显示了如何使用NSTable在后台加载图像。 另外,它应该是一个很好的如何不让你的图像混合匹配。