UIImageView in custom UICollectionViewCell returning nil all the time

后端 未结 5 1809
既然无缘
既然无缘 2020-12-29 05:02

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:

相关标签:
5条回答
  • 2020-12-29 05:17

    Well, this is odd. I know a solution, but I don't quite understand why it makes a difference. I had the same exact setup and the same problem. The IBOutlet was getting set to nil for the UIImageView, but not the UILabels.

    Change your declaration for the UIImageView to be a strong property instead of an instance variable.

    @property (strong) IBOutlet UIImageView* imageView;
    

    This solved the issue for me. Clearly there is something with the way that UIImageView is connected / instantiated from the storyboard. As an added 'weird' factor, I use the same setup of ivars with a UITableViewCell and have no issue, only in the UICollectionViewCell

    0 讨论(0)
  • 2020-12-29 05:21

    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.

    0 讨论(0)
  • 2020-12-29 05:37

    I had the similar problem and it's been solved by adding the following code in the DeviceImageCell

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

    Unfortunately I haven't managed to get _imageview initialised without this code addition.

    0 讨论(0)
  • 2020-12-29 05:38

    Also check this one,

    So now when you declare Custom CollectionView Cell in its Storyboard you need to specify the Attribute named "Identifier" under Collection Reusable View to some String. Now this may sound weired but , Check if name of Identifier is not same as Collection View Cell's class name. Class/File name of Cell and Cell Identifier must be Different.

    That really worked for me , hence posting.

    0 讨论(0)
  • 2020-12-29 05:39

    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"];
    
    0 讨论(0)
提交回复
热议问题