【发布时间】:2015-08-08 22:56:57
【问题描述】:
我正在尝试将图像从文档目录加载到UICollectionView。它的工作原理:流畅,快速....(笑)。但是我遇到了一个问题:当我打电话给[collectionView reloadData] 时,图像会闪烁(一次)。这是我的代码:
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView_ cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = NSStringFromClass([AFMyRecentCollectionViewCell class]);
AFMyRecentCollectionViewCell *cell = (AFMyRecentCollectionViewCell*)[collectionView_ dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
AFMyRecentObject *recent = [[AFRecentManager sharedInstance].arrayRecent objectAtIndex:indexPath.row];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [self databasePathWithPathComponent:[NSString stringWithFormat:@"%@.jpg", recent.id_film]];
if ([fileManager fileExistsAtPath:filePath] == YES) {
image = [UIImage imageWithContentsOfFile:filePath];
}
dispatch_async(dispatch_get_main_queue(), ^{
if (image) {
cell.imageView.image = image;
} else {
cell.imageView.image = [UIImage imageNamed:@"loadding.png"];
}
});
});
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
- (NSString *)databasePathWithPathComponent:(NSString*)pathComponent {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:pathComponent];
return path;
}
【问题讨论】:
-
顺便说一句,从技术上讲,您应该确保
cell在UIImage被实例化时还没有被另一个NSIndexPath重用。最有可能的是,因为您正在从本地存储中检索,所以这不太可能成为问题,但如果您要发起任何网络请求,当在蜂窝网络上快速滚动时,这会突然成为一个非常现实的问题。因此,使用上述模式时要非常小心,除非您确信在异步更新正在进行时不能重用单元格。
标签: ios objective-c image uicollectionview uicollectionviewcell