使用xib创建UICollectionViewCell子类

Pie*_*ero 46 iphone xib ios uicollectionview uicollectionviewcell

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

@interface MyCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UILabel *label;
@end
Run Code Online (Sandbox Code Playgroud)

另外我在文件所有者自定义类中链接了MyCell接口构建器中的类,并且我添加了一个UILabel,然后在我的UICollectionViewviewDidLoad中我这样做:

[self.collectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"MyCell"];

UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"MyCell"];
Run Code Online (Sandbox Code Playgroud)

除此之外:

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell*)[cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];


cell.label.text = @"Cell Text";


return cell;
}
Run Code Online (Sandbox Code Playgroud)

但是这不起作用,我收到此错误:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x907eca0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label.'
Run Code Online (Sandbox Code Playgroud)

我做错了什么?如何将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;
}
Run Code Online (Sandbox Code Playgroud)

per*_*ter 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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 使用`static`是一种不好的做法.静态变量是为所有实例共享的.同一类的第二个视图控制器不会加载.xib文件,因为`nibMyCellloaded`将被第一个设置为`YES`. (5认同)
  • 你不能只在viewDidLoad上调用registerNib一次,而不是每次集合视图要求一个单元格时都进行检查吗? (4认同)

Aut*_*ots 20

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

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