2014-09-05 47 views
0

我正在使用UICollectionView来显示一组图像。图像从网上加载。我从联机的JSON文件中获取图像URL。这些图像大小不同,我使用了一个流程图将图像放在一起。这里面临的挑战是,在加载之前,您将不知道图像的确切大小。我使用SDWebImage下载和缓存图像。我使用布尔值来检查加载哪些图像。每个图像加载后,我告诉collectionview重新加载图像在其相应的索引路径。现在的问题是图像的加载是否正确,但是当我滚动collectionview的时候,单元格都会搞砸了。下面是一些代码:从网站加载图像并在collectionview中显示

这是我计算每个单元格的大小:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(NHBalancedFlowLayout *)collectionViewLayout preferredSizeForItemAtIndexPath:(NSIndexPath *)indexPath 
    { 

if (didLoadImage == YES) { 
    return [loadedImage size]; 
    } 
else 
    { 
    return CGSizeMake(300, 140); 
    } 
} 

这里是在图像加载并设置:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
GalleryCell *customCell = [collectionView 
          dequeueReusableCellWithReuseIdentifier:@"cell" 
          forIndexPath:indexPath]; 

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[galleryLargeLinks objectAtIndex:indexPath.row]]]; 

customCell.backgroundColor = [UIColor blackColor]; 

[customCell.imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"placeholder"] success:^(NSURLRequest *request, NSHTTPURLResponse *response,UIImage *image) 
{ 
    loadedImage = image; 
    didLoadImage = YES; 
    [customCell.imageView setImage:image]; 
    [collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]]; 

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) 
{ 
    NSLog(@"fail"); 
    [activityIndicator stopAnimating]; 
}]; 
return customCell; 
} 

回答

0

UICollectionViewCell's被重新使用时,他们滚动屏幕。因此,由于您正在使用异步块加载它们,因此在准备好时可能会将单元分配给另一个indexPath。如果您愿意,您可以继续使用setImageWithURLRequest:,但是,您应该添加其他检查以查看indexPath在加载时是否仍然是您所期望的。事情是这样的:

[customCell setIndexPath:indexPath]; 
__weak GalleryCell *weakCell = cell; 
__weak CollectionView *weakCollectionView = collectionView; 
[customCell.imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"placeholder"] success:^(NSURLRequest *request, NSHTTPURLResponse *response,UIImage *image) 
{ 
    if([weakCell.indexpath isEqual:indexPath]){ 
     [weakCell.imageView setImage:image]; 
     [weakCollectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]]; 
    } 

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) 
{ 
    [activityIndicator stopAnimating]; 
}]; 

至于collectionView:layout:preferredSizeForItemAtIndexPath:,你需要去有关检查完全不同。一种选择可能是让你的缓存映像关闭你的数据源,所以你可以检查数据源数组中的值,看看它是否在缓存中。如果是,则抓取图像,否则返回默认值。这是太多的代码写出来的,但基本上你应该检查你的数据源/缓存,而不是随时可以改变的两个随机变量BOOLUIImage

+0

感谢您的回复。但我如何exatly比较weakcell.indexpath到indexpath?没有setindexpath方法。 – user3687 2014-09-06 04:31:21

+0

你需要在你的CustomCell类上创建一个属性 - > NSIndexPath * indexPath; – 2014-09-06 21:18:44

相关问题