UICollectionView以错误的顺序加载图像一秒钟

时间:2015-03-05 14:01:53

标签: ios objective-c uicollectionview

我有一个带有自定义单元格的UICollectionView,它有一些标签和一个UIImageView,数据从一些Json下载然后我填充我的单元格,问题是当我再次向上滚动一些单元格的图像变化一秒钟进入一个错误的(另一个产品),然后他们再次重置为正确的。我使用以下库https://github.com/nicklockwood/AsyncImageView为UIImageView使用Lazy Loading有没有人有同样的问题? 我填充单元格的代码如下:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    [self performSelector:@selector(test) withObject:nil];

    cell.backgroundColor = [UIColor whiteColor];


    // Configure the cell
    FidelityProducts *item = _feedItems[indexPath.row];
    //load the image

    urlImg = [NSURL URLWithString:item.urlImg];
    cell.img.showActivityIndicator = true;
    cell.img.imageURL = urlImg;
    cell.titolo.text = item.nomeProdotto;
    cell.codice.text = item.codice;
    cell.prezzo.text = item.prezzo;

    UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, cell.frame.size.width, 1)];
    bottomBorder.backgroundColor = [UIColor redColor];

    [cell.contentView addSubview:bottomBorder];


    return cell;
}

2 个答案:

答案 0 :(得分:1)

您需要覆盖自定义prepareForReuse课程中的UICollectionView,并将图片设置为nil。这应该可以解决您的问题:

- (void)prepareForReuse {
    [super prepareForReuse];

    [self.img setImage:nil];
}

不确定这个延迟加载UIImageView是如何工作的,也许您还需要将imageUrl设置为nil

希望它适合你。祝你好运!

答案 1 :(得分:0)

我知道你提问已经有一段时间了,但是我遇到了类似的问题,没有LazyLoad。

我使用一些标识符设置了我的单元格的标记,稍后我在调度队列中使用以确保我加载了相同的单元格。

这是我的代码:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

static NSString *cellIdentifier = @"cvCell";


UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.backgroundColor=[UIColor colorWithRed:237.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1];
for (UIView *vw in [cell subviews])
{
    [vw removeFromSuperview];
}


    NSURL *url = [NSURL URLWithString:[[self.dataArray objectAtIndex:indexPath.row] imageURL]];
    NSInteger evID =[[self.dataArray objectAtIndex:indexPath.row] ID].integerValue ;
    [cell setTag:evID];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{


        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        UIImageView *imagem = [[UIImageView alloc] initWithFrame:CGRectMake([GRAPHICS SCREEN_X], [GRAPHICS SCREEN_Y],106,106 )];

        dispatch_sync(dispatch_get_main_queue(), ^{
//here is the trick for loading the right image

            if (cell.tag==evID) {


            [imagem setBackgroundColor:[UIColor clearColor]];
            [imagem setImage:image];
            [cell addSubview:imagem];
            [cell setNeedsLayout];
            }

        });
    });



return cell;
}

希望这有助于其他人