2014-09-05 46 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

相關問題