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

23 objective-c ios uicollectionviewcell

好吧,在我的故事板上我已经用3个单元格创建了一个UICollectionView.我为其制作了一个自定义类的单元格之一显然扩展了UICollectionViewCell:

在此输入图像描述

我在ViewDiDApear中注册了这个类:

[self.collectionView registerClass:[DeviceImageCell class] forCellWithReuseIdentifier:@"Cell1"];
Run Code Online (Sandbox Code Playgroud)

此外,我已将imageView添加到该特定单元格,并在我的自定义类中添加了该imageView的插座.当我制作自定义单元格时会出现问题,它会忘记我的故事板中设置的所有内容,即背景颜色,我的图像视图所在的位置等等.因此,我的imageView始终返回nil.

-(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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*upt 49

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

然而,对于那些发现这个和具有相同问题的人

这是registerClass你的电话viewDidAppear

[self.collectionView registerClass:[DeviceImageCell class] forCellWithReuseIdentifier:@"Cell1"];
Run Code Online (Sandbox Code Playgroud)

您已在Interface Builder中注册该类,因此调用将registerClass:forCellWithReuseIdentifier:替换IB创建的条目.

删除此行将解决此问题.

  • 赞美主! (2认同)
  • 如果是笔尖,您必须使用以下方法注册笔尖:`[self.collectionView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellWithReuseIdentifier:@"CustomCellIdentifier"]; ` (2认同)

atu*_*tri 11

nib如果你使用的是这样的话,你应该注册自定义单元格 -

所以它将是:

[self.collectionView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellWithReuseIdentifier:@"CustomCellIdentifier"];
Run Code Online (Sandbox Code Playgroud)

代替:

[self.collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"CustomCellIdentifier"];
Run Code Online (Sandbox Code Playgroud)