Exception when adding UICollectionViewController to UITabbarController

311 views Asked by At

I'm new to iOS Programming and hope you can help me.

I get a

'NSInvalidArgumentException'

when trying to add a UICollectionViewController into my UITabbarController..

'UICollectionView must be initialized with a non-nil layout parameter'

The thing is I did initialize my CollectionView with a FlowLayout... here is the Code with MatchesCell being my UICollectionViewCell implementation

[self.collectionView registerClass:[MatchesCell class] forCellWithReuseIdentifier:@"MatchesCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(200, 140)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView initWithFrame:[self.tabBarController.view frame]  collectionViewLayout:flowLayout];`

I also tried to call initWithFrame with [[UIScreen mainScreen] bounds] or a CGRect I manually created, didn't work either...please help!

Thanks in advance!

2

There are 2 answers

0
Allan Weir On

It looks like you might be initialising two UICollectionViewControllers. The first line in your code is [self.collectionView registerClass:...] meaning that one already exists before you get to the final line of your code which is [self.collectionView initWithFrame:.. collectionViewLayout:..].

If you're making the collection view in a storyboard double check it has a valid layout set in it's properties, which you will find in the right panel of interface builder. Otherwise double check the rest of your code for anywhere you may be creating a UICollectionView before you get to this code. Any of the init methods, viewDidLoad, viewWillAppear or viewDidAppear might be good places to start.

Finally, try adding an exception breakpoint which will hopefully show you the exact line where the app crashes. https://developer.apple.com/library/ios/recipes/xcode_help-breakpoint_navigator/articles/adding_an_exception_breakpoint.html

0
u09cs47 On

CollectionViewController Initialization should be like the following,

 UICollectionViewLayout *myLayout = [[UICollectionViewLayout alloc] init];        
CollectionViewController *collectionViewController = [[CollectionViewController alloc] initWithCollectionViewLayout:myLayout];

Inside the CollectionViewController lifecycle methods like "viewDidLoad", add the following,

[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];        
self.view.backgroundColor = [UIColor whiteColor];    
self.collectionView.backgroundColor = [UIColor clearColor];        
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];        
flowLayout.itemSize = CGSizeMake(CGRectGetWidth(self.collectionView.frame)/2 - 20,     
CGRectGetWidth(self.collectionView.frame)/2 - 20);
self.collectionView.collectionViewLayout = flowLayout;

This should solve your problem. Thanks