Search code examples
iosuicollectionviewcustom-cell

Registering Custom Collection View Cell in UIView


I have the identical code from the answer to this question. I am trying to implement a custom view cell and it is doing so and works up until the point it casts the cell and tries to assign properties of my custom view cell (because it is still sees the cell as a UICollectionViewCell rather than CustomViewCell).

The log error that returns still gives the problem associated with registering the custom cell at viewDidLoad/loadView:

-[UICollectionViewCell imageView]: unrecognized selector sent to instance 0x1658c540

I am calling the collection view in a UIView, rather than a UIViewController, so there is no class method for viewDidLoad. I tried to implement the register in a method that I know is called first.

How do I manage to get the custom cell class registered? And for that matter, how do I make methods that get run once at the beginning of the instance like a viewDidLoad method?

Let me know if more code is necessary; I will update the question.

EDIT_1:

Turns out I was declaring it in older code I haven't combed over in a while. However, @Wyatt got the logic I needed, however it seems that the NSLog doesn't get run for that method. Anyway I found that I was registering twice in some older code I hadn't combed over in a while that gets called after the init. @Neil's answer is also correct. Thanks guys!


Solution

  • If the log is telling you that UICollectionViewCell doesn't know what imageView is, then it's accurately telling you that you're creating UICollectionViewCell items, instead of CustomViewCells. The log reports the actual class of the object, not what it may or may not be casted to in code.

    You're either failing to register the cell class when you create the UICollectionView or failing to create the right type of cell.

    UICollectionView *collectionView = [[UICollectionView alloc] init... // omitted
    
    [collectionView registerClass:[CustomViewCell class] forCellWithReuseIdentifier:@"CustomIdentifier"];
    

    getting cells in cellForItemAtIndexPath::

    CustomViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomIdentifier" forIndexPath:indexPath];