我正在尝试创建一个UICollectionViewCell
带有链接 xib 的子类,我已经这样做了:我创建了一个新的 xib 文件并UICollectionViewCell
在其中添加了一个,然后我创建了这个子类文件:
@interface MyCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
我还在文件所有者自定义类中链接了MyCell
界面生成器中的类,并且添加了一个UILabel
,然后在我的UICollectionView
viewDidLoad 中执行以下操作:
[self.collectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"MyCell"];
UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"MyCell"];
以及在这个:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell*)[cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.label.text = @"Cell Text";
return cell;
}
但是这不起作用,我收到此错误:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x907eca0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label.'
我做错了什么?如何将UICollectionViewCell
子类连接到 xib,并将其显示在UICollectionView
?
编辑:
我已经这样做了:
- (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;
}