使用xib创建UICollectionViewCell子类

时间:2013-01-22 19:58:32

标签: ios iphone uicollectionview xib uicollectionviewcell

我正在尝试创建一个链接了xib的UICollectionViewCell子类,我这样做: 我已经创建了一个新的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;
}

2 个答案:

答案 0 :(得分:48)

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

在界面构建器上选择单元格

enter image description here

然后在身份检查员

enter image description here

随后将您的标签与您的媒体资源相关联。 (我想你已经这样做了)

然后我建议验证您是否已在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;
    }

答案 1 :(得分:20)

您可以在本文档中找到答案UICollectionView adding UICollectionCell

  

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

相关问题