I'm trying to create a UICollectionViewCell
subclass with linked a xib, I have do this:
I have create a new xib file and I have add a UICollectionViewCell
in it, then I have create this subclass file:
@interface MyCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
Also I have linked in the file owner custom class the MyCell
class in interface builder, and I have added a UILabel
, then in my UICollectionView
viewDidLoad I do this:
[self.collectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"MyCell"];
UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"MyCell"];
As well as in this:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell*)[cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.label.text = @"Cell Text";
return cell;
}
However this doesn't work, I receive this error:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x907eca0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label.'
What did I do wrong? How can I connect a UICollectionViewCell
subclass to a xib, and display it in a UICollectionView
?
EDIT:
i have do this:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"MyCell";
static BOOL nibMyCellloaded = NO;
if(!nibMyCellloaded)
{
UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil];
[cv registerNib:nib forCellWithReuseIdentifier:identifier];
nibMyCellloaded = YES;
}
MyCell *cell = (MyCell*)[cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.labelCell.text = @"Text";
return cell;
}
Make sure the cell on the .xib file know what's the type of the cell.
Select the cell on your interface builder
and then on the identity inspector
Subsequently associate your labels with your properties. (I think you already did that)
Then I'd recommend to verify if you already loaded the .xib file on your cellForItemAtIndexPath:
method
NSString *identifier = @"MyCell";
static BOOL nibMyCellloaded = NO;
if(!nibMyCellloaded)
{
UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil];
[cv registerNib:nib forCellWithReuseIdentifier:identifier];
nibMyCellloaded = YES;
}