UICollectionView cellForItemAtIndexPath不注册单元格
我想使用UICollectionViewCell
,因为我想显示的是一个图像。 我可以使用UIColor colorWithImage:
将图像添加到单元格UIColor colorWithImage:
在UICollectionViewCell
的contentView
属性上。
在我的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
。 那是因为我想改变视图的背景颜色。 我不知道是什么问题,但有人可以看看我的代码,并帮助我? 我一直试图弄清楚这一点,绝对没有运气。
如果你只是想显示一个图像,你不需要做任何的子类化,你可以用colorWithPatternImage:
设置单元格的backgroundColor
。 注册类如下:
[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; }
在这个例子中,结果是一个UIImages
array
。
如果您在应用程序中使用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; }
希望以上将有所帮助。
尝试设置一个断点
[self.collectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"MyCell"];
我会猜测你的loadView(你的意思是viewDidLoad?)方法没有被调用,所以类是从来没有注册collectionView。
如果您的集合视图连接到故事板,并且委托和数据源已设置,并且您为数据源和委托提供了必要的方法,则添加注册调用将使
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
返回一个UICollectionView
而不是你自己的子类。 所以做,但不是两个。
在代码中设置您的单元标识符名称