UICollectionView中的iOS声明失败

我收到错误…

*** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:], /SourceCache/UIKit/UIKit-2372/UICollectionView.m:2249 

当试图显示一个UICollectionView。

造成它的线条是…

 static NSString *CellIdentifier = @"Cell"; UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; 

在出列时发生错误。

没有其他的错误,所以我很难知道从哪里开始。

任何人都可以阐明这一点?

你需要注册如下:

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

一直在阅读文档(应该可能已经做到了这一点:))

无论如何,我正在使用的collectionView是在一个单独的xib文件(不是一个故事板),从文档…

 Important: You must register a class or nib file using the registerClass:forCellWithReuseIdentifier: or registerNib:forCellWithReuseIdentifier: method before calling this method. 

谢谢

确保如果你使用registerNib:方法:

 UINib *nibH = [UINib nibWithNibName:HEADER_ID bundle:nil]; [collectionView registerNib:nibH forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADER_ID]; 

也就是说,在nib文件中,当您select顶级集合可重用视图时,请使用属性检查器,并确保Identifier设置为您传递给withReuseIdentifier:参数的相同值。

我有同样的问题。 这是我如何解决它。

移动

[self.pictureCollectionView registerNib:[UINib nibWithNibName: bundle:nil] forCellWithReuseIdentifier:reuseID]

- (void)viewDidLoad

而不是方法- (void)awakeFromNib

更换

 NSString *CellIdentifier = @"Cell"; 

 static NSString *CellIdentifier = @"Cell"; 

当使用多个具有唯一ReuseIdentifiers的UICollectionViews时,我看到这个错误popup。 在ViewDidLoad中,你想注册每个CollectionView的reuseIdentifier像这样:

 [_collectionView1 registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionView1CellIdentifier"]; [_collectionView2 registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionView2CellIdentifier"]; 

然后,当你到“ – (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath”你想确保你不要尝试为collectionView2设置一个单元格作为collectionView2的reuseIdentifier,否则会得到这个错误。

不要这样做 :(或者collectionView2会看到错误的标识符,并在看到它所期望的标识符之前发现一个错误)

 UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView1CellIdentifier" forIndexPath:indexPath]; if(collectionView != _collectionView1){ cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView2CellIdentifier" forIndexPath:indexPath]; } cell.backgroundColor = [UIColor greenColor]; return cell; 

做这个

 UICollectionViewCell *cell; if(collectionView == _collectionView1){ cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView1CellIdentifier" forIndexPath:indexPath]; }else{ cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView2CellIdentifier" forIndexPath:indexPath]; } cell.backgroundColor = [UIColor greenColor]; return cell;