Bertie Bertie - 2 months ago 10x
iOS Question

Initializing a custom UICollectionViewCell

I have a custom

that has a custom background view which is drawn using one of several colour schemes. The colour scheme for the background view is set in my custom initializer
for the View.

I have a similar custom initialiser in my
subclass but I can't figure out how to call this initialiser when I am setting up the cell in

Can anyone help me do this? Or offer alternative solution for passing this Dictionary of colours into the Cell to pass on to the subView?

EDIT to show more detail:

This is what I have in my UICollectionView VC:

In ViewWillAppear:

[self.collectionView registerClass:[OPOLawCollectionViewCell class] forCellWithReuseIdentifier:CELL_ID];
self.colourPalette = [OPOColourPalette greenyColourPalette];

In cellForItemAtIndexPath:

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_ID forIndexPath:indexPath];
OPOLawCollectionViewCell *lawCell = (OPOLawCollectionViewCell *)cell;

MainLevel *level = self.collectionData[indexPath.row];
lawCell.delegate = self;
lawCell.colourPalette = self.colourPalette;

In my Custom UICollectionViewCell

- (id)initWithFrame:(CGRect)frame
self = [super initWithFrame:frame];
if (self)
// get background view
OPOLawBook *lawBookView = [[OPOLawBook alloc]initWithFrame:CGRectMake(0, 0, 200, 265) andColourPalette:self.colourPalette];

But that doesn't work - I guess because the propertys are not set up.

If I change the last line to this, then it works fine:

OPOLawBook *lawBookView = [[OPOLawBook alloc]initWithFrame:CGRectMake(0, 0, 200, 265) andColourPalette:[OPOColorPalette greenyColorPalette]];

So i guess I need to use a custom intialiser here but I cant figure out how to call it , or from where...



Yuo have to register your customCells in collectionView:

[self.collectionView_ registerClass:[YourCustomClass class]

And then in your method cellForItemAtIndexPath:

 YourCustomClass *cell = (YourCustomClass *)[collectionView 
         dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];

It is done because collectionView might have 1000 cells and 10 visible. You don't keep all of them initialized and reuse when possible.


You should set colorPaletter after you deque the reusable cell. Think of it as a container which can hold any color. You need to determine (by indexpath) what color to paint.