【发布时间】:2014-09-05 19:08:37
【问题描述】:
我正在使用 UICollectionView 来显示一组图像。图片是从网上加载的。我从在线 JSON 文件中获取图像 URL。图像大小不同,我使用流程布局将图像放在一起。这里的挑战是,在加载图像之前,您不会知道图像的确切大小。我使用 SDWebImage 下载和缓存图像。我使用一个布尔值来检查加载了哪些图像。加载每个图像后,我告诉 collectionview 在其相应的 indexpath 处重新加载图像。现在的问题是图像确实加载正确但是当我滚动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;
}
【问题讨论】:
标签: ios uicollectionview sdwebimage