形象一个UITableView混错 - XML解析

问题描述:

编辑:其实图像出现罚款,当我滚动,他们弄混这是...形象一个UITableView混错 - XML解析

我解析的链接的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; 
} 

任何想法我做错了什么? 任何帮助都非常感谢。谢谢!

当你问一个可重复使用的电池,如果它不是零它是您已分配并添加子视图到它的内容查看...你应该首先删除所有子视图中,你cellForRow细胞

您的问题是,如果单元格不是nil(即,您已成功重新使用已经滚动屏幕的单元格),则不会正确设置customImage指针(因为它是一个类实例变量,它具有它创建的最后一个单元的值)。因此,定义一些非零常数为kCustomImageTag,然后修改if声明cellForRowAtIndexPath是:

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]; 
} 

设置tag当您创建customImage并使用tag来检索重用UITableViewCell现有customImage

+2

非常感谢!完美的作品 –

..

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在后台加载图像。此外,它应该是一个很好的如何不让你的图像混合匹配。