ios - 使用 xib 创建 UICollectionViewCell 子类

标签 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;
}

最佳答案

确保 .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;
    }

关于ios - 使用 xib 创建 UICollectionViewCell 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14466959/

相关文章:

ios - 使用带有 UIViewController 的 Xcode 5 停止 [tableView loadData] 取消选择行

iphone - 如何在 iPhone 中绘制饼图

ios - Core Data 数据模型中的订单实体

objective-c - 从数组中加载章节标题

objective-c - 在模拟器中播放 - objective-c

html - 如何将 HTML 标签添加到 UITextView Swift Xcode 中的字符串

ios - 如何设计和设置 UICollectionView 的高度并防止其折叠?

ios - setSelectionIndicatorImage 尺寸错误

iphone - 在移动和 Web 服务器之间同步对象列表的最佳解决方案

ios - 如何确定我需要为 UICollectionView 设置的高度?