图像在 UITableView 中混淆 - XML 解析 [英] Images getting mixed up in a UITableView - XML parsing

查看:29
本文介绍了图像在 UITableView 中混淆 - XML 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上图像看起来不错,只是当我滚动时它们被混淆了......

我正在解析一个 XML 文件,其中包含指向我放入 UITable 的图像的链接.出于某种原因,图片变得完全混乱,当我向下滚动表格时,其中一些甚至开始发生变化!这是我用于 UITable 的代码:

I'm parsing an XML file with links to images which I'm putting into a UITable. For some reason the pictures are getting completely mixed up and when I scroll down the table some of them even start to change! Here's the code I'm using for my 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;
}

知道我做错了什么吗?任何帮助都受到严重赞赏.谢谢!

Any idea what I'm doing wrong? Any help is seriously appreciated. Thx!

推荐答案

你的问题是如果单元格不是 nil (即你已经成功重用了一个已经滚出屏幕的单元格),您没有正确设置 customImage 指针(因为它是一个类实例变量,它具有它创建的最后一个单元格的值).因此,为 kCustomImageTag 定义一些非零常量,然后将 cellForRowAtIndexPath 中的 if 语句修改为:

Your problem is that if the cell is not nil (i.e. you've successfully reused a cell that has scrolled off the screen), you're not setting the customImage pointer properly (since it is a class instance variable, it has the value from the last cell it created). So, define some non-zero constant for kCustomImageTag and then modify the if statement in cellForRowAtIndexPath to be:

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

在创建 customImage 时设置 tag 并使用该 tag 检索重用的现有 customImageUITableViewCell.

Set the tag when you create customImage and use that tag to retrieve an existing customImage in the reused UITableViewCell.

这篇关于图像在 UITableView 中混淆 - XML 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆