33

我正在尝试使用UICollectionViewCell,因为我想要显示的只是一张图片。我可以使用'属性将图像添加到单元格中UIColor colorWithImage:UICollectionViewCellcontentView

在我的loadView方法中,我正在注册单元格,如下所示: [self.collectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"MyCell"];

下面是我的cellForItemAtIndexPath方法:

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

当我运行它时,一旦它到达出队行,它就会崩溃并出现以下错误:

*** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:]

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier MyCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

我厌倦了设置自定义单元格,并将其用作类,我得到了同样的错误。我的自定义单元格是 UICollectionViewCell 的子类,除了默认的initWithFrame. 那是因为我只想更改视图的背景颜色。我不确定问题是什么,但有人可以看看我的代码并帮助我吗?我一直试图弄清楚这一点,但完全没有运气。

4

5 回答 5

61

如果你只是想显示一张图片,你不需要做任何子类化,你可以设置单元格backgroundColorcolorWithPatternImage:. 像这样注册类:

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

然后像这样使用它:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithPatternImage:[self.results objectAtIndex:indexPath.row]];
    return cell;
}

在此示例中,结果是arrayUIImages

于 2012-09-30T05:04:34.157 回答
15

如果您在应用程序中使用 xib,则在您的 viewdidLoad 方法中添加以下内容

    [self.myCollectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CellIdentifier"];

否则,如果您使用情节提要,请添加以下内容

  [self.myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"CellIdentifier"];

最后添加这个(如果没有)

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

以上希望对您有所帮助。

于 2014-06-18T06:23:19.640 回答
8

尝试设置断点

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

我猜你的 loadView (你的意思是 viewDidLoad 吗?)方法没有被调用,所以这个类永远不会在 collectionView 中注册。

于 2012-10-08T21:26:18.353 回答
7

如果您的集合视图连接到情节提要上并且在那里设置了委托和数据源,并且您为数据源和委托提供了必要的方法,那么添加注册调用会使

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath

返回 aUICollectionView而不是您自己的子类。所以要么做,但不能两者兼而有之。

于 2013-02-06T09:51:23.553 回答
4

将您的单元格标识符名称设置为代码

在此处输入图像描述

于 2014-02-15T09:22:29.650 回答