我正在使用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