在下面的代码中,我从文本文件下载图像 URL,将其存储在 NSMutableArray 中,然后从 CellforItemAtIndexPath 中的这些 URL 下载图像。但是,当我上下滚动时,有那么一小会儿,错误的图像出现在了错误的位置。它会在一秒钟后纠正,但我想摆脱那个滚动问题。这是代码:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"Cell2";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
AsyncImageView *recipeImageView = (AsyncImageView *)[cell viewWithTag:100];
UILabel *titleView = (UILabel *)[cell viewWithTag:101];
titleView.numberOfLines = 3;
UIImageView *overlay = (UIImageView *)[cell viewWithTag:111];
FXBlurView *blurView = (FXBlurView *)[cell viewWithTag:110];
blurView.tintColor = [UIColor colorWithRed:51.0 green:51.0 blue:51.0 alpha:1];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
hi = [self videoTitle];
images = [self firstPhoto];
// switch to a background thread and perform your expensive operation
// switch back to the main thread to update your UI
dispatch_async(dispatch_get_main_queue(), ^{
NSString *imgSrc;
NSString *url = images[indexPath.row];
imgSrc = url;
if (imgSrc != nil && [imgSrc length] != 0 ) {
[recipeImageView setImageWithURL:[NSURL URLWithString:images[indexPath.row]] placeholderImage:[UIImage imageNamed:@"red.png"]];
}
else {
NSLog(@"noimage");
recipeImageView.image = [UIImage imageNamed:@"red.png"];
}
titleView.text = hi[indexPath.row];
});
});
return cell;
// recipeImageView.image = [UIImage imageNamed:[videoList objectAtIndex:indexPath.row]];
}
有什么想法吗?谢谢。
最佳答案
我不确定 AsyncImageView
是什么,所以首先让我把您的问题当作 UIImageView
来回答:
在您的回调 block 中(当您返回到主队列时),您指的是 recipeImageView
。但是,如果用户在下载期间滚动,则 cell
对象已被重用。
进入回调后,您必须假设所有对 View 的引用(cell
、recipeImageView
、blurView
、等指向错误的东西。您需要使用数据模型找到正确的 View 。
一种常见的方法是使用 NSIndexPath 来查找单元格:
UICollectionViewCell *correctCell = [collectionView cellForItemAtIndexPath:indexPath]:
UIImageView *correctRecipeImageView = (UIImageView *)[correctCell viewWithTag:100];
/* Update your image now… */
请注意,只有当 indexPath
始终保证指向相同的内容时,这才会起作用 - 如果用户可以插入/删除行,那么您也需要找出正确的 indexPath ,因为它也可能发生了变化:
NSIndexPath *correctIndexPath = /* Use your data model to find the correct index path */
UICollectionViewCell *correctCell = [collectionView cellForItemAtIndexPath:correctIndexPath]:
UIImageView *correctRecipeImageView = (UIImageView *)[correctCell viewWithTag:100];
/* Update your image now… */
也就是说,如果 AsyncImageView
是应该为您处理所有这些的其他类,那么您只需在主线程上调用 setImageWithURL: placeholderImage:
,它应该代表您处理所有异步加载。如果没有,我想推荐 SDWebImage 库,它可以:https://github.com/rs/SDWebImage
关于ios - UICollectionView 在滚动时重新加载错误的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884952/