我在下载 gif
图像并添加到 Collection View 时遇到问题。
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
中设置它们之前,您必须加载所有图像。
假设创建一个包含所有 gif
图像的 NSArray
。图像加载成功后,将它们设置到单元格中。
通过直接观察您的代码,我发现您在 cellForItemAtIndexPath
方法中从主包加载了一张图像。所以很明显,它会花费一些时间(纳秒)。但当单元格中有大量数据时,这也被认为是大的。
而且有可能那条线
[NSData dataWithContentsOfFile:[[NSBundle mainBundle]
当您滚动得非常非常快时,将返回 nil
。
如果还不清楚,请添加评论。
编辑:
后台加载图片不会影响UI,滚动会更流畅。
此外,将 try-catch
block 放在该方法中以检查您错过了什么。
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);
}
关于ios - 将许多 gif 加载到 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26398081/