48

我正在尝试创建一个UICollectionViewCell带有链接 xib 的子类,我已经这样做了:我创建了一个新的 xib 文件并UICollectionViewCell在其中添加了一个,然后我创建了这个子类文件:

@interface MyCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UILabel *label;
@end

我还在文件所有者自定义类中链接了MyCell界面生成器中的类,并且添加了一个UILabel,然后在我的UICollectionViewviewDidLoad 中执行以下操作:

[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;
}
4

2 回答 2

48

确保 .xib 文件中的单元格知道单元格的类型。

选择界面生成器上的单元格

在此处输入图像描述

然后在身份检查员上

在此处输入图像描述

随后将您的标签与您的属性相关联。(我想你已经这样做了)

然后我建议验证您是否已经在cellForItemAtIndexPath:方法中加载了 .xib 文件

NSString *identifier = @"MyCell";    

    static BOOL nibMyCellloaded = NO;

    if(!nibMyCellloaded)
    {
        UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil];
        [cv registerNib:nib forCellWithReuseIdentifier:identifier];
        nibMyCellloaded = YES;
    }
于 2013-01-22T21:03:35.553 回答
20

您可以在本文档UICollectionView 添加 UICollectionCell中找到答案。

只有 StoryBoard 中的 UICollectionView 内部有 UICollectionViewCell。如果使用 XIB,使用 CellName.xib 创建一个新的 XIB,将 CollectionViewCell 添加到其中,指定 UICollectionView 自定义类的名称。之后使用 registerNib.Sample 代码:https ://github.com/lequysang/TestCollectionViewWithXIB

于 2013-05-22T14:02:27.103 回答