The Collection View provides a flexible way to present content to the user. Similar to a table view, a collection view gets data from custom data source objects and displays it using a combination of cell, layout, and supplementary views. A collection view can display items in a grid or in a custom layout that you design. In this tutorial we will display a number of colored cells in a collection view.
Open Xcode and create a new Single View Application. For product name, use iOS7CollectionViewTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.
First, Let's create our Collection View. Go to the Storyboard. Select and delete the current view controller. Next, drag a collection view controller to the canvas. The canvas should look like this.
When we Create a collection view controller in the storyboard, it has set up the delegate and data source outlets of the collection view to point to your collection view controller. Go to ViewController.h and change the UIViewController into an UICollectionViewController
@interface ViewController : UICollectionViewController
Select the Collection View Controller and go to the Identity Inspector, under the custom class section change the Class to ViewController.
Select the little square on the top-left of the collection view controller. This represents the collection view cell. Go to the Attribute Inspector and under the Collection Reusable View change the Identifier in coloredCell.
Later on, we will need this identifier in our code. In ViewController.m in the interface section declare the following property.
@interface ViewController ()
@property (nonatomic) BOOL cellColor;
We will use this boolean to select a background color of our cells. To conform to the UIColectionViewDataSource protocol we will need to implement two required methods. First add the collectionView:numberOfItemsinSection method.
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
We will create 50 cells. Next add the collectionView:cellForItemAtIndexPath method.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"coloredCell" forIndexPath:indexPath];
cell.backgroundColor = (self.cellColor) ? [UIColor redColor] : [UIColor blueColor];
self.cellColor = !self.cellColor;
We initialize a collection view cell with our previously created Cell Identifier. Next we check our boolean. If it is set to YES the background color of the cell is set to red, otherwise it is set to blue. Build and Run the project and you should see the collection view with colored cells.
You can download the source code of the iOS7CollectionViewTutorial at the ioscreator repository on github.