我正在尝试使用 UICollectionViewCell,因为我只想显示图像。我可以使用 UICollectionViewCell 的 contentView 属性上的 UIColor colorWithImage: 将图像添加到单元格。
在我的 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 之外没有任何实现。那是因为我只想更改 View 的背景颜色。我不确定问题出在哪里,但有人可以看看我的代码并帮助我吗?很长一段时间以来,我一直在努力解决这个问题,但一点运气都没有。
最佳答案
如果你只想显示一个图像,你不需要做任何子类化,你可以用colorWithPatternImage:设置单元格的backgroundColor。像这样注册类(class):
[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;
}
在此示例中,results 是 UIImages 的 array。
关于objective-c - UICollectionView cellForItemAtIndexPath 未注册单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12657421/