将许多gif加载到UICollectionView

时间:2014-10-16 07:00:25

标签: ios xcode uicollectionview uicollectionviewcell

我下载gif图片并添加到集合视图时遇到问题。 gif图像下载得很好,但是当我尝试非常快速地滚动时,它会崩溃

请帮忙。我有两个解决方案

    /*
    cellForGif.layer.borderColor = [[UIColor colorWithRed:54.0/255.f green:56.0/255.f blue:67.0/255.f alpha:1.0]CGColor];
    cellForGif.layer.borderWidth = 0.7;
    FLAnimatedImage __block *gifImage = nil;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        gifImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%li", (long)indexPath.row] ofType:@"gif"]]];

        dispatch_async(dispatch_get_main_queue(), ^{

            cellForGif.gifImage.animatedImage = gifImage;
            cellForGif.linkOnGif = [self.linksArrayOnGifs objectAtIndex:indexPath.row];
           //gifImage = nil;
        });
    });
    return cellForGif;
     */
    cellForGif.layer.borderColor = [[UIColor colorWithRed:54.0/255.f green:56.0/255.f blue:67.0/255.f alpha:1.0]CGColor];
    cellForGif.layer.borderWidth = 0.7;
    FLAnimatedImage *gifImage = nil;
        gifImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%li", (long)indexPath.row] ofType:@"gif"]]];
            cellForGif.gifImage.animatedImage = gifImage;
            cellForGif.linkOnGif = [self.linksArrayOnGifs objectAtIndex:indexPath.row];
            //gifImage = nil;

    return cellForGif; 

1 个答案:

答案 0 :(得分:3)

您需要改变方法。

您必须在UICollectionViewCell中设置之前加载所有图像。

我们假设创建NSArray包含所有gif张图片。成功加载图像后,将它们设置为单元格。

通过直接从您的代码中观察,我发现您使用cellForItemAtIndexPath方法从主包中加载图像。因此很明显它需要一些时间(纳秒)。但是当单元格中存在大量数据时,这也被认为很大。

行可能

[NSData dataWithContentsOfFile:[[NSBundle mainBundle]
当您非常快速地滚动时,

将返回nil

如果仍然不清楚,请添加评论。

修改

在后台加载图片不会影响用户界面,滚动也会更顺畅。

此外,在该方法中放置try-catch块以检查您错过了什么。

    cellForGif.layer.borderColor = [[UIColor colorWithRed:54.0/255.f green:56.0/255.f blue:67.0/255.f alpha:1.0]CGColor];
    cellForGif.layer.borderWidth = 0.7;

    @try {
        FLAnimatedImage __block *gifImage = nil;        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            gifImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%li", (long)indexPath.row] ofType:@"gif"]]];

            dispatch_async(dispatch_get_main_queue(), ^{

                cellForGif.gifImage.animatedImage = gifImage;
                cellForGif.linkOnGif = [self.linksArrayOnGifs objectAtIndex:indexPath.row];
                //gifImage = nil;
            });
        });
    }
    @catch (NSException *exception) {
        NSLog(@"Exception :%@",exception.debugDescription);
    }