图像在UITableView中混淆 - XML解析

时间:2013-01-21 14:04:50

标签: ios objective-c uitableview

编辑:实际上图片看起来不错,当我滚动它们混合起来时......

我正在解析一个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;
}

知道我做错了什么吗? 任何帮助都非常感谢。 THX!

3 个答案:

答案 0 :(得分:3)

您的问题是,如果单元格不是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检索重用的customImage中的现有UITableViewCell

答案 1 :(得分:0)

当你要求一个可重复使用的单元格时,如果它不是零,那么它是你已经分配的单元格并将子视图添加到它的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];
}

答案 2 :(得分:0)

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

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