UICollection视图单元格图像在水平滚动时发生变化

时间:2015-10-16 13:29:33

标签: ios uiimageview grand-central-dispatch uicollectionviewcell collectionview

我正在使用url数组来为图像加载到集合视图中。滚动集合视图时图像正在变化。如何解决这个问题?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"RecentProductCell";
    RecentProductCell *recentCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

            recentCell.recentProductImg.image = nil;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                NSString *imageurl = [[latestProducts valueForKey:@"image"]objectAtIndex:indexPath.item];
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]];

                dispatch_sync(dispatch_get_main_queue(), ^{
                    recentCell.recentProductImg.image = [UIImage imageWithData:imageData];
                });
            });

    }

2 个答案:

答案 0 :(得分:0)

替换dispatch_sync(dispatch_get_main_queue(), ^{ recentCell.recentProductImg.image = [UIImage imageWithData:imageData]; });

dispatch_sync(dispatch_get_main_queue(), ^{
                if ( imageData )
                {
                  UIImage *urlImage = [[UIImage alloc] initWithData:imageData];
                  RecentProductCell *recentCell = (id)[collectionView cellForItemAtIndexPath:indexPath];
                  if (recentCell)
                       [recentCell.recentProductImg setImage:urlImage];
                }
            });

请告诉我这是否适合您。

答案 1 :(得分:0)

cell.imageView.image = nil;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^(void) {

        NSString *imageurl = [[latestProducts valueForKey:@"image"]objectAtIndex:indexPath.item];
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]];

        UIImage* image = [[UIImage alloc] initWithData:imageData];
        if (image) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (cell.tag == indexPath.row) {
                     cell.imageView.image = image;
                     [cell setNeedsLayout];
                 }
             });
         }
    });

将此代码写入collectionView

的cellForRowAtIndexPath方法