Gee*_*eek 2 objective-c ios uicollectionview uicollectionviewcell ios7
UICollectionView
用于显示图像.它工作正常.
问题是当我滚动时UICollectionView
,一些可见的单元格现在是不可见的,当我向后滚动以便它们再次可见时,我看到它们没有正确显示.
所以发生的imageA
是在索引0并且imageB
在索引1处.现在在滚动并且在再次加载这些单元格时返回原始滚动位置时,它们的位置被切换或者两个单元具有相同的图像.
原来 :
重新加载单元格后:
代码:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell"
forIndexPath:indexPath];
DLog(@"url at index %d : %@", indexPath.row, ((MyObject *)[self.list.array objectAtIndex:indexPath.row]).imageUrl);
MyObject *object = (MyObject *)[self.list.array objectAtIndex:indexPath.row];
// Get image in separate thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Get image to display
UIImage * tempImage = object.image;
if (tempImage)
{
// Run code to set image to UIImageView in main thread only.
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = tempImage;
});
}
else
{
// Download failed.
DLog(@"Downloaded image is nil.");
}
});
return cell;
}
Run Code Online (Sandbox Code Playgroud)
我记录了图片网址的值,并记录了正确的值.
我也使用了这个技巧,但线程和线程之间的索引弄得一团糟,所以我搜索了一下,我在GitHub上找到了一个很棒的库.
您只需要进入#import <SDWebImage/UIImageView+WebCache.h>
项目,并且只需使用以下代码即可在下载图像时定义占位符:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell"
forIndexPath:indexPath];
DLog(@"url at index %d : %@", indexPath.row, ((MyObject *)[self.list.array objectAtIndex:indexPath.row]).imageUrl);
MyObject *object = (MyObject *)[self.list.array objectAtIndex:indexPath.row];
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
return cell;
}
Run Code Online (Sandbox Code Playgroud)
它还可以缓存下载的图像并为您提供出色的性能.
希望它能帮到你!