自定义UICollectionViewCell中的UIImageView始终返回nil

在我的故事板确定我已经做了3个单元格的UICollectionView。 我为它做了一个自定义类的单元之一显然扩展了UICollectionViewCell:

在这里输入图像说明

我在ViewDiDApear中注册了这个类:

[self.collectionView registerClass:[DeviceImageCell class] forCellWithReuseIdentifier:@"Cell1"]; 

此外,我已经添加了一个imageView到特定的单元格和我的自定义类中的imageViewsockets。 当我制作自定义单元格时,会忘记在故事板中设置的所有内容,即背景颜色,图像视图的位置等等。 因此,我的imageView一直返回零。

 -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { if(indexPath.row == 0) { static NSString *identifier = @"Cell1"; DeviceImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; UIImage *image = [UIImage imageNamed:@"dysart-woods-full.jpg"]; cell.imageview.image = image; cell.backgroundColor = [UIColor blueColor]; //cell.imageview.image = image; return cell; } else if(indexPath.row == 1) { static NSString *identifier = @"Cell2"; UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; return cell; } else { static NSString *identifier = @"Cell3"; UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; UIImageView *imageView = (UIImageView *)[cell viewWithTag:1]; imageView.image = [UIImage imageNamed:@"dysart-woods-full.jpg"]; return cell; } } 

你可能早就解决了这个问题。

但是对于那些发现这一点,并具有相同的问题

这是你的viewDidAppearregisterClass调用

 [self.collectionView registerClass:[DeviceImageCell class] forCellWithReuseIdentifier:@"Cell1"]; 

您已经在Interface Builder中注册了该类,因此对registerClass:forCellWithReuseIdentifier:的调用正在replace由IB创build的条目。

删除这条线将解决这个问题。

你应该注册自定义单元的nib如果你使用这样的一个 –

所以这将是:

 [self.collectionView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellWithReuseIdentifier:@"CustomCellIdentifier"]; 

代替:

 [self.collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"CustomCellIdentifier"]; 

好吧,这很奇怪。 我知道一个解决scheme,但我不太明白为什么它有所作为。 我有相同的确切设置和相同的问题。 IBOutlet被设置为零的UIImageView,而不是UILabels。

更改您的声明为UIImageView是一个强大的属性,而不是一个实例variables。

 @property (strong) IBOutlet UIImageView* imageView; 

这为我解决了这个问题。 很显然,UIImageView从故事板连接/实例化的方式是有的。 作为一个额外的“怪异”因素,我使用与UITableViewCell相同的ivars设置,没有问题,只有在UICollectionViewCell

我有类似的问题,并已通过在DeviceImageCell添加以下代码解决

 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _imageview = [[UIImageView alloc] initWithFrame:self.contentView.bounds]; [self.contentView addSubview:_imageview]; } return self; } 

不幸的是我没有设法得到_imageview初始化没有这个代码添加。