我正在使用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;
}
感謝您的回覆。但我如何exatly比較weakcell.indexpath到indexpath?沒有setindexpath方法。 – user3687 2014-09-06 04:31:21
你需要在你的CustomCell類上創建一個屬性 - > NSIndexPath * indexPath; – 2014-09-06 21:18:44