Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewController Programmatically crashing with non-nil layout parameter error

I am creating a UICollectionViewController programmatically. No, I don't want to use IB and Storyboards like every tutorial out there. I just want to use plain code.

Here is what I have in my viewDidLoad:

// UICollectionView
    UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    [aFlowLayout setItemSize:CGSizeMake(200, 140)];
    [aFlowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:aFlowLayout];
    [self.collectionView setDelegate:self];
    [self.collectionView setDataSource:self];
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth];
    [self.collectionView registerClass:[PUCImageGridCell class] forCellWithReuseIdentifier:CollectionViewCellIdentifier];

I have implemented the required delegate methods and I still get this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'
like image 967
Nic Hubbard Avatar asked Apr 02 '13 22:04

Nic Hubbard


1 Answers

This is what I use to initialize a UICollectionViewController:

- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout

You do not need to instantiate the collectionView the controller will do it for you. Set the frame after calling this or you can override and set the frame inside:

- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout{
     self = [super initWithCollectionViewLayout:layout];
     if (self) {
         // additional setup here if required.
     }
     return self;
}

I prefer to use the autolayout constraints.

like image 56
Samuel Avatar answered Sep 28 '22 09:09

Samuel