Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImageView in custom UICollectionViewCell returning nil all the time

OK in my story board I have made a UICollectionView with 3 cells. One of the cells I made a custom class for that obviously extends the UICollectionViewCell:

enter image description here

And I registered the class in my ViewDiDApear:

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

Also I have added an imageView to that specific cell and an outlet for that imageView in my custom class. Problem occurs when I make my custom cell it forgets everything that was set in my storyboard, aka the background color, where my image view is and so on. Because of this my imageView returns nil all the time.

-(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;
    }
}

2 Answers

You have probably long solved this issue.

However for those finding this and having the same issue

it is the registerClass call in your viewDidAppear

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

You are already registering the class in Interface Builder, so the call to registerClass:forCellWithReuseIdentifier: is replacing the entry created by IB.

Removing this line will fix the issue.

like image 166
Chad Edrupt Avatar answered Sep 14 '25 07:09

Chad Edrupt


You should register the custom cell's nib if you are using one like this-

So it will be:

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

instead of:

[self.collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"CustomCellIdentifier"];
like image 41
atulkhatri Avatar answered Sep 14 '25 09:09

atulkhatri