防止UICollectionView重绘

我的目标是使用UICollectionView显示一排延迟加载的缩略图(数字未知),然后用户可以水平滚动缩略图。

我正在使用下面的代码来实现接近我后,但我得到一个错误。

前4个缩略图加载没问题,但是当您滚动缩略图时,会开始按照随机顺序绘制。

我正在努力获得以下内容:

 Item 1 ----- Item 2 ----- Item 3 ---- Item 4 

我喜欢它,所以单元格只能绘制一次,类似于使用UITableView时所获得的结果。 我只想要UICollectionView重新加载数据,当我要求它。

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; UIView *tmpView; if([self.selectedEffects isEqualToString:@"Effects"]){ int index = indexPath.row; NSLog(@"%i",index); tmpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 70, 90)]; [tmpView setBackgroundColor:[UIColor clearColor]]; UIImageView *imageViewWithEffect = [[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 60, 60)]; imageViewWithEffect.layer.cornerRadius = 10.00; imageViewWithEffect.clipsToBounds = YES; UILabel *labelEffect = [[UILabel alloc] initWithFrame:CGRectMake(0, 65, 70, 20)]; [labelEffect setText:[[self.activeEffectsArray objectAtIndex:index] objectAtIndex:1]]; labelEffect.textAlignment = NSTextAlignmentCenter; labelEffect.textColor = [UIColor whiteColor]; [labelEffect setFont:[UIFont boldSystemFontOfSize:8]]; UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; [activityIndicator setFrame:CGRectMake(0, 0, 60, 60)]; activityIndicator.alpha = 1.0; [activityIndicator startAnimating]; UIButton *buttonSelect = [UIButton buttonWithType:UIButtonTypeCustom]; [buttonSelect setFrame:CGRectMake(0, 0, 60, 90)]; [buttonSelect setTag:index]; [buttonSelect addTarget:self action:@selector(applyEffects:) forControlEvents:UIControlEventTouchUpInside]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ UIImage *imageWithEffect = [self editImage:[[self.activeEffectsArray objectAtIndex:indexPath.row] objectAtIndex:0] ImageToEdit:self.thumbnailImage]; dispatch_async(dispatch_get_main_queue(), ^{ [imageViewWithEffect setImage:imageWithEffect]; [activityIndicator removeFromSuperview]; }); }); [tmpView addSubview:imageViewWithEffect]; [tmpView addSubview:labelEffect]; [tmpView addSubview:activityIndicator]; [tmpView addSubview:buttonSelect]; } [cell addSubview:tmpView]; return cell; } 

您每次都在向单元添加子视图。 这是不正确的,因为单元格可能已被重用。 检查子视图是否已经创build,如果已经存在,请进行修改。 你可以通过inheritanceUICollectionViewCell或者使用viewWithTag:viewWithTag:前者更可取)。 有数百个这样的例子,所以我不会在这里重温。

您也正在调度块中引用相同的视图。 这也是不正确的,因为单元可能在块被调用的时候被重用。 相反,使用indexPath再次获取单元格,并以这种方式进行修改。

最后,您可能需要考虑在后台线程上舍入图像angular落,而不是使用layer.cornerRadius – 这种方法会导致图像被混合,当您一次显示大量图像时,可能会导致不连贯的滚动animation。