Search code examples
iosobjective-cios7xcode5iphone-developer-program

Can I integrate UIViewController and UICollectionViewController in one app?


In an app I'm making, I'm trying to mix a UIViewContoller and a UICollectionViewController in two different view controllers. The CollectionViewController Cells won't show up in the app. I was wondering how I incorporate it in to my interface in the viewcontroller.h.

Current ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
- (IBAction)cameraButtonClicked:(id)sender;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;


@end

Solution

  • @interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource>
    - (IBAction)cameraButtonClicked:(id)sender;
    @property (strong, nonatomic) IBOutlet UIImageView *imageView;
    @property (strong, nonatomic) UICollectionView *collectionView
    @end
    

    Then, on your ViewController.m:

    - (void)viewDidload{
        self.collectionView = ({
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
            flowLayout.itemSize = CGSizeMake(300, 107);
            flowLayout.minimumLineSpacing = 10.f;
            [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowLayout];
        });
    
        [self.collectionView setAlwaysBounceVertical:YES];
        [self.collectionView setContentInset:UIEdgeInsetsMake(60, 0, 0, 0)];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.collectionView];
    
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    }
    

    Also, I think you're kind of confused on the term "View Controller" and "View." A UICollectionViewController is the object you drag onto your Storyboard from the Objects Library (on your Utilities panel). A UICollectionView is a subclass of UIScrollView (just like UITableView) that incorporates a series of methods that give it it's behavior.

    Please note that, since you're conforming to the UICollectionViewDataSource and the UICollectionViewDelegate protocols, you should implement the @required methods from those protocols:

    1. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;
    2. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
    3. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

    Hope I helped.