xcode UICollectionView:无法识别的选择器发送到实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21993338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 04:41:36  来源:igfitidea点击:

UICollectionView: Unrecognized selector sent to instance

iosobjective-cxcode

提问by user3249524

I am getting this error. *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICollectionViewCell label]: unrecognized selector sent to instance 0x1eead660'I am using a nib file as my cell and trying to displays the cells correctly. I am guessing that I am not returning cells correctly, but I am not too sure. Any help will be appreciated.

我收到此错误。 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICollectionViewCell label]: unrecognized selector sent to instance 0x1eead660'我使用 nib 文件作为我的单元格并尝试正确显示单元格。我猜我没有正确返回单元格,但我不太确定。任何帮助将不胜感激。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView    cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    NSMutableArray *data = [sections objectAtIndex:indexPath.section];

    cell.label.text = [data objectAtIndex:indexPath.item];

    return cell;
 }

回答by Aaron Brager

UICollectionViewCell doesn't have a property called label.

UICollectionViewCell 没有名为 的属性label

Perhaps you meant:

也许你的意思是:

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

Assuming you subclassed UICollectionViewCell, added label, and called your subclass Cell.

假设您对子类进行了子类化UICollectionViewCell、添加label和调用Cell

回答by Clay Bridges

Your nib file probably needs to be connected to your custom class ('Cell'?) somehow. That done, you'd call:

您的 nib 文件可能需要以某种方式连接到您的自定义类('Cell'?)。完成后,您会调用:

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

As it stands right now, you are getting a vanilla UICollectionViewCellobject back from dequeue..., and when you try to use it as a Cell, you get problems.

就目前而言,您正在UICollectionViewCell从 返回一个普通对象dequeue...,当您尝试将其用作 时Cell,您会遇到问题。

BTW, generally, your registerClasscode should not go in cellForItemAtIndexPath. It only needs to be called once per view, e.g.

顺便说一句,一般来说,你的registerClass代码不应该进入cellForItemAtIndexPath. 每个视图只需要调用一次,例如

static NSString *cellIdentifier = @"Cell";

@implementation YourCollectionViewController

// ...

- (void)viewDidLoad
{
     [self.collectionView registerClass:[Cell class] forCellWithReuseIdentifier:@"Cell"];   
}

// ...

@end