将许多gif加载到UICollectionView
当我下载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;
你需要改变你的方法。
您必须先加载所有图像,然后再在UICollectionViewCell
设置它们。
假设创建一个NSArray
包含所有gif
图像。 成功加载图像后,将它们设置为单元格。
通过直接从您的代码中观察,我看到您在cellForItemAtIndexPath
方法中从主包加载图像。 因此很明显它需要一些时间(纳秒)。 但是当单元格中存在大量数据时,这也是相当大的。
并且它可能是那条线
[NSData dataWithContentsOfFile:[[NSBundle mainBundle]
滚动非常快时会返回nil
。
如果仍然不清楚,请添加评论。
编辑:
在后台加载图像不会影响UI,滚动会更顺畅。
还要在该方法中使用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) }