Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView must be initialized with a non-nil layout parameter

Tags:

I'm new to UICollectionView and I'm following a tutorial I found on the web but I'm stuck on an error I can't figure out. Here's a bit of context.

In the debugger I can see that following is happening:

  • numberOfSectionsInCollectionView: is called and I return 1
  • collectionView:numberOfItemsInSection: is called and I return the size of the model (20)
  • collectionView:layout:sizeForItemAtIndexPath: gets called once for each item in the model
  • collectionView:layout:insetForSectionAtIndex: is called
  • collectionView:cellForItemAtIndexPath: gets called and it crashes on this line...

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    

with this error...

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'

When I pause execution on that line and check the console it appears that there is a layout...

(lldb) po collectionView.collectionViewLayout
(UICollectionViewLayout *) $4 = 0x07180fd0 <UICollectionViewFlowLayout: 0x7180fd0>

The UICollectionView is part of the one and only scene in the storyboard. In viewController.m there are no other UICollectionViews created by any means.

Does anyone have any ideas?

like image 672
Murray Sagal Avatar asked Oct 28 '12 16:10

Murray Sagal


2 Answers

This worked for me :

UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];     [aFlowLayout setItemSize:CGSizeMake(200, 140)];     [aFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal]; myCollectionViewController = [[MyCollectionViewController alloc]initWithCollectionViewLayout:flowLayout]; 

If you are creating UICollectionView programmatically a layout is required.

like image 96
Maz Naiini Avatar answered Nov 15 '22 11:11

Maz Naiini


As it turns out the problem was with registerClass:. I had this:

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

but it should have been this:

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

So the dequeue method was creating a UICollectionView instead of a UICollectionViewCell.

like image 34
Murray Sagal Avatar answered Nov 15 '22 13:11

Murray Sagal