user1646683
user1646683

Reputation: 25

Adding UICollectionViewController's view to a super view "programmatically"

I am trying to do a simple task of adding a UICollectionView to the main view, programmatically.

I first created a "PhotosViewController.h/h/xib" files (of type UIViewController), removed the view that was given and added a UICollectionView as the primary view of this controller & then changed the superclass of "PhotosViewController.h" to UICollectionViewController.

I followed the first 6 steps given in this tutorial: http://skeuo.com/uicollectionview-custom-layout-tutorial and then jumped to step 14. What I am trying to do is just to bring up this view when the user clicks on a segmented control button.

if ([segmentedControl selectedSegmentIndex]==3){
    //Photos View Controller
    pvc=[[PhotosViewController alloc] init];
    NSLog(@"Photos segment is chosen!");
    [[self view] addSubview:pvc.view]; **//Line 5**
}

But the program throws up an exception on reaching Line 5.

This is the log message that I get.

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

Looks like, I am missing something very fundamental here. I have been searching for any kind of solution to this problem for the past one hour and I couldn't find anything.

Any help is much appreciated.

Upvotes: 1

Views: 2325

Answers (2)

jrturton
jrturton

Reputation: 119272

[[PhotosViewController alloc] init];

I assume this is where you are creating your collection view controller. The designated initialiser for this class is initWithCollectionViewLayout:, where you'd pass in a layout object. You aren't passing one in, so it complains. Try using that initialiser, or, in your subclass, make sure you call this instead of [super init], and pass in a new flow layout object.

Upvotes: 1

RegularExpression
RegularExpression

Reputation: 3541

I'm not clear on where you initialized your collection view, but it ought to look something like this:

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0.0f,
                                                                    230.0f,
                                                                    [self viewWidth],
                                                                    [self viewHeight]) 
                                    collectionViewLayout:flowLayout];

Unless you have a more extended UICollectionViewFlowLayout.

From the message you're getting, it looks as though you're not giving it a UICollectionViewFlowLayout in your collectionViewLayout:

Upvotes: 0

Related Questions