iOS UICollectionView Example Tutorial

Filed Under: iOS

In this tutorial we’ll look into iOS UICollectionView component and develop a basic application out of it.

UICollectionView

UICollectionView is similar to UITableView except the fact that it’s more customisable. The main difference between a UICollectionView and a UITableView is that a UICollectionView can display more than one column and it supports horizontal scrolling.

A UICollectionView is used to customise the layout in any way we wish. The basic UICollectionView resembles to a GridView from android in many ways.

The most common place where a UICollectionView layout is seen is in the Photos App.

UICollectionView components

UICollectionView consists of the following major components.

  1. UICollectionViewCell : Just like UITableViewCells, these cells are the subviews of the UICollectionView. Our content is displayed in these cells only. The cells are dequeued as the user leaves the screen
  2. Supplementary Views : It consists of other important components such as labels, section headers and footers that are used to define and divide the content area

UICollectionView Example

Let’s take advantage of Storyboards to implement a Collection View in our View Controller.

For that drag the Collection View onto the View Controller and drag it to cover the full screen below the navigation bar.

Change the background color to black so that the bounds of the Collection View are perfectly visible.

A UICollectionViewCell is visible at the top left of the CollectionView as seen in the image below.

ios simple ui collection view

The UICollectionView cell is too small. Let’s make it bigger from the attributes inspector in the right panel. We’ve shown how to do it in the image below.

UICollectionView tutorial

We’ve defined the cell identifier too that would be used in the ViewController.swift file.

As usual we need to control click and drag the Collection View to the dock ViewController button to connect the data source and the delegates. This can be done in the code too, but we prefer doing it here itself.

The Storyboard is ready. We’ll add the collection view outlet to the ViewController.swift from the assistant editor as shown below.

ios simple UICollectionView example connections

The ViewController.swift is given below.


import UIKit


let reuseIdentifier = "CellIdentifer";


class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //UICollectionViewDelegateFlowLayout methods
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat
    {
        
        return 4;
    }
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat
    {
        
        return 1;
    }
    
    
    //UICollectionViewDatasource methods
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return 100
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
    
        cell.backgroundColor = self.randomColor()
        
        
        return cell
    }
    

    // custom function to generate a random UIColor
    func randomColor() -> UIColor{
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }


}

That’s a lot of code to digest at once! Let’s break it down.

We’ve added all the protocol methods used besides the UIViewController.

Note: We’ve chosen UIViewController as the parent class and added a collection view in it. There’s a UICollectionViewController class too that can be used by replacing all instances of ViewController object (including the screen in the storyboards) with the UICollectionViewController.

Now before we look into the UICollectionViewDelegateFlowLayout methods, once switch to the storyboard and focus the collection view and change the number of items to 2. An image like the one shown below would be seen.

iOS UICollectionView Example Tutorial

We need to customise the spacing between the cells so that it looks more cleaner. Hence the two methods are implemented. The values returned are CGFloat values. After playing around with different values, we found the ones given above as the best fit for the present iOS app.

The UICollectionViewDatasource methods are used to define the number of sections and the number of items. We’ve randomly assigned the numbers here.

The function collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell is similar to the one in the TableView example. We’ve assigned a random background value to each cell using the randomColor() function by choosing a random R G B and returning the UIColor instance.

Running the application gives us the following output.

UICollectionView example app

This brings an end to iOS UICollectionView tutorial. You can download the iOS SimpleCollectionView app code from the link below.

Reference: Official Documenation

Comments

  1. Sandeep says:

    The example which you have given is very nice but if you can provide some more different idea in which we can implement CollectionView, not complete code only if you give some hint.

    1. Anupam says:

      Hi Sandeep,
      Have you used the Instagram iOS Application? When you view anyone’s profile, the photos are displayed in a CollectionView. Try implementing that on your own while I work on writing a tutorial on the same. Good Luck 🙂

      Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages