大佬教程收集整理的这篇文章主要介绍了ios – UICollectionView将图像添加到单元格,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用的方法是检查图像URL是否为空,然后将ImageView添加到单元格上.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemATindexPath:(NSIndexPath *)indexPath { if (question.picture != (id)[NSNull null]) { //add AsyncImageView to cell imageView.contentMode = UIViewContentModeScaleAspectFill; imageView.clipsToBounds = YES; imageView.tag = IMAGE_VIEW_TAG; [cell addSubview:imageView]; [[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView]; imageView.imageURL = [NSURL URLWithString:question.picture]; } }
对于那些没有图像的单元格,单元格应如下所示:
https://dl.dropboxusercontent.com/u/5753236/Stackoverflow/good.png
但是,其中一些仍然会在其上添加带有裁剪图像的ImageView,导致如下所示:
https://dl.dropboxusercontent.com/u/5753236/Stackoverflow/bad.png
我尝试过使用SDWebImage,但仍未解决问题.
另一个问题是,当我向下滚动UICollectionView时,我会看到一些图像首先显示为上面显示的图像,然后在加载完成后更改为正确的图像,我只是不知道导致问题的原因.
>第一种方式(好方法):您将uICollectionViewCell子类化,并为子类提供“imageView”属性.然后在CustomcatollectionViewCell.m文件中执行此操作:
// Lazy loading of the imageView - (UIImageView *) imageView { if (!_imageView) { _imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds]; [self.contentView addSubview:_imageView]; } return _imageView; } // Here we remove all the custom stuff that we added to our subclassed cell -(void)prepareForReuse { [super prepareForReuse]; [self.imageView removeFromSuperview]; self.imageView = nil; }
然后在你的ViewController中你必须像这样声明你的collectionViewCells的新类:
[self.collectionView registerClass:[CustomcatollectionViewCell class] forCellWithReusEIDentifier:@"cell"];
它将确保在重用时正确删除图像,并且更容易在collectionView委托中设置单元格.
>第二种方式(脏方式),每次加载新单元格时都会删除视图:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemATindexPath:(NSIndexPath *)indexPath { for (UIView *subview in [cell.contentView subviews]) { [subview removeFromSuperview]; } if (question.picture != (id)[NSNull null]) { //add AsyncImageView to cell imageView.contentMode = UIViewContentModeScaleAspectFill; imageView.clipsToBounds = YES; imageView.tag = IMAGE_VIEW_TAG; [cell.contentView addSubview:imageView]; [[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView]; imageView.imageURL = [NSURL URLWithString:question.picture]; } }
这种方式要容易得多,但我不推荐它:P
现在尝试一下,让我知道你的bug是如何演变的.
以上是大佬教程为你收集整理的ios – UICollectionView将图像添加到单元格全部内容,希望文章能够帮你解决ios – UICollectionView将图像添加到单元格所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。