我在这一整个下午,我无法想象它,所以你的帮助会很棒!我有一个自定义的UICollectionViewCell,里面填充了我在飞行中创建的图像。图像的路径存储在分析和查询完成后,我打电话[self.collectionView reloadData].
如何正确加载自定义UICollectionViewCell上的图像?
在我cellForItemAtIndexPath我有以下代码:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MovieCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
// Configure the cell
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"original_title" ascending:YES];
[self.moviesforWatchlist sortUsingDescriptors:[NSArray arrayWithObjects:sort, nil]];
cell.userInteractionEnabled = YES;
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[cell addSubview:spinner];
NSDictionary *movie = self.moviesforWatchlist[indexPath.row];
NSString *moviePosterPath = movie[@"poster_path"];
NSString *posterURL = [NSString stringWithFormat:@"http://image.tmdb.org/t/p/w342%@", moviePosterPath];
NSURL *posterImage = [NSURL URLWithString:posterURL];
UIImage *cachedImage = [self.imageCache objectForKey:posterImage];
if (cachedImage) {
cell.imageView.image = cachedImage;
}
else if (cell.imageView.image == nil) {
cell.imageView.image = [UIImage imageNamed:@"default_collectionviewcell.jpeg"];
dispatch_queue_t downloadQueue = dispatch_queue_create("get image data", NULL);
dispatch_async(downloadQueue, ^{
[spinner startAnimating];
NSData *imageData = [NSData dataWithContentsOfURL:posterImage];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
MovieCollectionViewCell *updateCell = (id)[collectionView cellForItemAtIndexPath:indexPath];
if (updateCell) {
updateCell.imageView.image = image;
[updateCell reloadInputViews];
[self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
}
});
[self.imageCache setObject:image forKey:posterImage];
});
}
[self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
return cell;
}
我打电话这样的查询方法:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self getWatchlistData];
[self.collectionView reloadData];
}
这会导致图像闪烁,直到图像加载到UICollectionViewCells。我希望显示在我的collectionviewcell中的图像按照字母顺序排列,因此我正在排序包含路径的阵列,在cellforitemsatindexpath
这是什么导致图像闪烁?或者是别的什么?非常感谢您的帮助!
不用担心!我非常感谢你的反馈。我刚开始学习Objective-C,iOS开发和编程,所以这些答案很棒。我知道我做错了什么,但是让它正常工作仍然取决于我。 关于这个......我认为它现在正在工作!我在对数组进行排序时,它在getWatchListData方法中填充(这似乎有很大的不同)。基本上,我做了所有的建议。唯一的问题是,在第一次加载时,有时单元格会填充错误的图像。任何想法如何我可以解决这个问题? – bienj0 2014-10-18 10:56:04
只有几个指针:首先,检查您的缓存是否正确填充。它可能在之前的运行中被错误填充,即使您的代码现在可能没问题。其次,注意细胞再利用问题,特别是如果您在滚动列表时看到相同的图像出现。我发现NSLog和断点对于追踪这类问题确实很有帮助。 – pbasdf 2014-10-18 22:48:24