2016-05-17 81 views
0

使用UICollectionView加载图像。UICollectionView滚动时图像发生变化

以下是我的代码。 ImageArray将包含每个必须加载的图像的url。而在我的代码,我试着给一个圆形边框围绕整个的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; 
} 

的问题,即时通讯面临的是,

  1. 如果即时滚动它horizo​​tally
  2. 内容被改变的图像圆形边框将呈现给collectionview的每个单元格,但圆形边框不会呈现给整个UICollectionView。

我该如何解决这个问题?

+0

使用SDWebImage, https://github.com/rs/SDWebImage – itsji10dra

+0

对于第二个问题,您将单元格的图层分配给'layer',这就是为什么边框不会呈现给整个UICollectionView。 – luiyezheng

+0

我该如何将它展示给整个UICollectionView?谢谢 – Roger

回答

2

UICollectionView将重用现有的单元格。因此,您的imageViewcollectionViewCell中可能会显示先前加载的图像。

它不是一个完美的解决方案,但开始下载喜欢

recipeImageView.image = nil; 

if ([ImageArray count] > 0) { 
1

您可以设置边框和圆角半径像集合视图,

collectionView.layer.borderWidth = 1.0; 
    collectionView.layer.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor; 
    collectionView.layer.cornerRadius = 4.0f; 

不要将其设置成cellForItemAtIndexPath。将其设置为viewdidload,以便加载一次,否则,每当单元格出现时,它会进行设置!

第二件事,如一条评论中的建议,您应该使用SDWebImage来缓存图像。

如果您使用自动布局,请确保设置了正确的约束条件。

希望这将有助于:)

1

你引用的单元格的标签,但所有小区的100这相同的标记值意味着你会得到不可预知的结果,这就是为什么你的形象是不断变化的。

1
UICollectionViewCell

是一种方法prepareForReuse之前给一个尝试像传递nil或默认图像imageView您应该覆盖并设置UIImageView的图像为nil

相关问题