ios – UICollectionView将图像添加到单元格

前端之家收集整理的这篇文章主要介绍了ios – UICollectionView将图像添加到单元格前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个项目,该项目使用UICollectionView来显示可能有也可能没有图像的数据.

我正在使用的方法是检查图像URL是否为空,然后将ImageView添加到单元格上.

  1. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3. if (question.picture != (id)[NSNull null]) {
  4. //add AsyncImageView to cell
  5. imageView.contentMode = UIViewContentModeScaleAspectFill;
  6. imageView.clipsToBounds = YES;
  7. imageView.tag = IMAGE_VIEW_TAG;
  8. [cell addSubview:imageView];
  9. [[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView];
  10. imageView.imageURL = [NSURL URLWithString:question.picture];
  11. }
  12. }

对于那些没有图像的单元格,单元格应如下所示:
https://dl.dropboxusercontent.com/u/5753236/Stackoverflow/good.png

但是,其中一些仍然会在其上添加带有裁剪图像的ImageView,导致如下所示:
https://dl.dropboxusercontent.com/u/5753236/Stackoverflow/bad.png

我尝试过使用SDWebImage,但仍未解决问题.

另一个问题是,当我向下滚动UICollectionView时,我会看到一些图像首先显示为上面显示的图像,然后在加载完成后更改为正确的图像,我只是不知道导致问题的原因.

请帮我解决这两个问题,我真的很感激你的帮助.

解决方法

首先,在单元格中添加图像的方式非常危险.原因是您的单元格正在被重用(例如滚动时或重新加载数据时),这些图像在重用时永远不会被删除.因此,您将开始在任何地方进行搜索,甚至可以达到您的单元格包含多次图像的位置.这有两种方法

>第一种方式(好方法):您将UICollectionViewCell子类化,并为子类提供“imageView”属性.然后在CustomCollectionViewCell.m文件中执行此操作:

  1. // Lazy loading of the imageView
  2. - (UIImageView *) imageView
  3. {
  4. if (!_imageView) {
  5. _imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
  6. [self.contentView addSubview:_imageView];
  7. }
  8. return _imageView;
  9. }
  10.  
  11. // Here we remove all the custom stuff that we added to our subclassed cell
  12. -(void)prepareForReuse
  13. {
  14. [super prepareForReuse];
  15.  
  16. [self.imageView removeFromSuperview];
  17. self.imageView = nil;
  18. }

然后在你的ViewController中你必须像这样声明你的collectionViewCells的新类:

  1. [self.collectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

它将确保在重用时正确删除图像,并且更容易在collectionView委托中设置单元格.
>第二种方式(脏方式),每次加载新单元格时都会删除视图:

  1. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3. for (UIView *subview in [cell.contentView subviews]) {
  4. [subview removeFromSuperview];
  5. }
  6.  
  7. if (question.picture != (id)[NSNull null]) {
  8. //add AsyncImageView to cell
  9. imageView.contentMode = UIViewContentModeScaleAspectFill;
  10. imageView.clipsToBounds = YES;
  11. imageView.tag = IMAGE_VIEW_TAG;
  12. [cell.contentView addSubview:imageView];
  13. [[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView];
  14. imageView.imageURL = [NSURL URLWithString:question.picture];
  15. }
  16. }

这种方式要容易得多,但我不推荐它:P

现在尝试一下,让我知道你的bug是如何演变的.

猜你在找的iOS相关文章