Fogmeister Fogmeister - 1 year ago 232
iOS Question

UICollectionViewCell subclass init never run

I have added a collection view in viewDidLoad like this...

self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 10, 10) collectionViewLayout:flowLayout];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.collectionView registerClass:[CameraCell class] forCellWithReuseIdentifier:CameraCellReuseIdentifier];
[self.collectionView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:self.collectionView];

And I have a UICollectionViewCell subclass called CameraCell with an init like this...

- (id)init
self = [super init];
if (self) {
// Add customisation here...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageChanged:) name:@"image" object:nil];

self.contentView.backgroundColor = [UIColor yellowColor];

self.imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
self.imageView.clipsToBounds = YES;
[self.imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.contentView addSubview:self.imageView];

NSDictionary *views = NSDictionaryOfVariableBindings(_imageView);

[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_imageView]|"

[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_imageView]|"
return self;

But when I run the app the collection view is there and I can scroll it but I can't see any cells. I have added a breakpoint in the cell's init and it never gets called. Is there another method I have to override?


When I log the cell in cellForItemAtIndexPath...

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
CameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CameraCellReuseIdentifier forIndexPath:indexPath];

NSLog(@"%@", cell);

return cell;

It displays the correct class...

<CameraCell: 0x1f07ba30; baseClass = UICollectionViewCell; frame = (0 20; 320 280); layer = <CALayer: 0x1f07bb40>>

Answer Source

The method you need to implement is - (id)initWithFrame:(CGRect)aRect

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download