[英]Images changes when UICollectionView is scrolled
Im using a UICollectionView to load images. 我正在使用UICollectionView加载图像。
Following is my code. 以下是我的代码。 ImageArray will contain the url for each images that has to be loaded. ImageArray将包含每个必须加载的图像的URL。 and In my code, Im trying to give a round border around the entire collectionview 在我的代码中,我试图在整个collectionview周围给出一个圆形边框
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
CALayer* layer = cell.layer;
[layer setCornerRadius:4.0f];
[layer setBorderColor:[UIColor colorWithWhite:0.8 alpha:1].CGColor];
[layer setBorderWidth:1.0f];
if ([ImageArray count] >0){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *data0 = [NSData dataWithContentsOfURL: [NSURL URLWithString:[ImageArray objectAtIndex:indexPath.row]]];
UIImage *image = [UIImage imageWithData: data0];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
recipeImageView.image = image;
});
});
}
[spinnerShow stopAnimating];
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
The problem that im facing is that, 我面临的问题是,
How can I sort this out? 我该如何解决呢?
UICollectionView
will reuse the existing cell. UICollectionView
将重用现有的单元格。 So there might be a possibility that your imageView
in collectionViewCell
will display the previous loaded image. 因此, collectionViewCell
中的imageView
可能会显示先前加载的图像。
Its not a perfect solution, but give a try like passing nil
or default image to imageView
before starting downloading like 它不是一个完美的解决方案,但是尝试像在开始下载之前先将nil
或默认图像传递给imageView
recipeImageView.image = nil;
before 之前
if ([ImageArray count] > 0) {
UICollectionViewCell
中的方法是prepareForReuse
,您应重写此方法并将UIImageView
的图像设置为nil
You can set border and corner radius to collection view like, 您可以为集合视图设置边框和拐角半径,例如
collectionView.layer.borderWidth = 1.0;
collectionView.layer.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor;
collectionView.layer.cornerRadius = 4.0f;
And don't set it in cellForItemAtIndexPath
. 并且不要在cellForItemAtIndexPath
设置它。 Set it in viewdidload
, so that it loads once, otherqwise it will set everytime when cell will deque! 在viewdidload
设置它,以便它加载一次,否则它将在每次单元出队时设置!
Second thing, as suggest in one comment you should use SDWebImage for caching the images. 第二件事,正如在一条评论中建议的那样,您应该使用SDWebImage来缓存图像。
Make sure you set right constraints if you are using autolayout. 如果使用自动版式,请确保设置正确的约束。
Hope this will help :) 希望这会有所帮助:)
您引用的是单元格的标记,但是所有单元格的标记值均为100。这意味着您将获得不可预测的结果,这就是图像不断变化的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.