Taking first plunge with collection views and am running into this error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
The code is very simple, as shown below. I can't for the life of me figure out what it is that I'm missing.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
The collection view controller was created using a nib and the delegates & datasources are both set to file's owner.
View Controller's header file is also really basic.
@interface NewMobialViewController_3 : UICollectionViewController <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@end
If you create it by code, you must create a custom
UICollectionViewCell
, Then, init aUICollectionView
,and useloadView
to set the view is theUICollectionView
that you create. If you create inviewDidload()
, it does not work. In addition, you can also drag aUICollectionViewController
, it saves a lot of time.You need to use same identifier between the dequeueReusableCellWithReuseIdentifier's argument and the UICollectionViewCell's property.
If you are using storyboard instead of xib, here are few steps.
In the ColletionViewDelegate.
That's it. You also don't want to add registerClass:forCellWithReuseIdentifier: which will cause element nil error.
Swift4.0
Whenever your
UITableViewCell
is xib at that time you must have to register withUITableView
.From the UICollectionView documentation for the dequeue method:
What fixed this for me was (roughly) same as Omar's answer, except I ended up creating a new UICollectionViewCell custom class and giving the Cell Reuse Indentifier a new / different name than the one that I had used elsewhere in the application. It worked immediately after that.