How to Create a UICollectionView Controller in iOS Swift?

In this tutorial, we will check out the basics of UICollectionViewController component and also learn the ins and outs of UICollectionView (introduced in iOS 6). Before that, let’s begin with some introductory part.

While learning Swift app development, you might have heard about UICollectionViewController while some of you don’t know. Let’s shed some light, UICollectionView Control is tableview kind of Control that introduced in iOS 6 to create a Grid-Like layout.

It works same like tableview, as tableview displays data in a single column layout, Collectionview displays data in a customizable layout. There are three components of collection views such as:

  • Cells – It shows a single item. We can instantiate collection view cell same as tableview cell.
  • Supplementary views: – Basically, it is an option and used to make header or footer view of sections.
  • Decorative views: – It is same as supplementary view, but not used to display any data. It just used to decorate view enhancing UI.

Let’s start code in XCODE

  1. Create project with “SOCollectionViewDemo” name

    Collection1

  2. Get UICollectionViewController and set as a RootViewController

    Collection2

  3. Assign ViewController.swift to storyboard as per given below.

    Collection3

    Collection4

  4. Add “collectionCell” Identifier for UICollectionViewCell, which will be used in CollectionView’s Delegate “cellForItemAtIndexPath”

    Collection5

  5. Now, integrate Delegate and DataSource in app, Datasource and Delegate return information about the number of items in the collection view shows selection, data populating.

    	//MARK: UICollectionViewDataSource
    	
    	override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        	return 1
    	}
    	
    	override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        	return 10
    	}
    	
    	override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        	let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
        	configureCell(cell, forItemAtIndexPath: indexPath)
        	return cell
    	}
    	
    	func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
        	cell.backgroundColor = UIColor.blackColor()
        	//3
        	let imgView = UIImageView(frame: CGRectMake(0, 0, layout.itemSize.width, layout.itemSize.height))
        	imgView.contentMode = .ScaleAspectFit
        	imgView.image = UIImage(named: "img1.jpg")
        	cell.addSubview(imgView)
        	
    	}
    	
    	override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        	let view =  collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
        	return view
    	}
     
    	//MARK: UICollectionViewDelegate
    	override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        	
    	}
    	
    	override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        	
    	}
    
  6. UICollectionViewFlowLayout Delegate should be used to manage a layout of CollectionViewCell, also we can manage top, left, bottom, right margin and size of UICollectionViewCell.

    For that, we declare global variable of UICollectionViewFlowlayout

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    and then manage height, width, and margin of UICollectionViewCell from viewDidLoad

    	override func viewDidLoad() {
        	super.viewDidLoad()
        	// Do any additional setup after loading the view, typically from a nib.
        	
        	layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        	layout.itemSize = CGSize(width: 90, height: 90)
        	self.collectionView?.collectionViewLayout = layout
    	}
    

    This will also manage by delegate too

    func collectionView(collectionView: UICollectionView,
                        	layout collectionViewLayout: UICollectionViewLayout,
                               	insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        	return UIEdgeInsetsMake(20, 10, 10, 10); //UIEdgeInsetsMake(topMargin, left, bottom, right);
    	}
    

     

    Collection7

    UICollectionViewFlowlayout will be managed by its Delegate too.

    	//MARK:- UICollectionViewDelegateFlowLayout
       func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        	return self.collectionViewLayout.collectionViewContentSize()
    	}
    	
    	func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) ->
        	CGFloat {
            	Return 30.0
    	}
    

    Collection8

    	func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        	return 30.0
    	}
    

    Collection9

    If we do not use delegate of UICollectionViewFlowlayout then it will get default setting of height, width, and margin from “Size Inspector”

    Collection 10

     

    At this point, you’ve now got a complete working example of UICollectionViewController. Hope, you got a complete idea of the fundamental steps of creating UICollectionViewController in Swift. Maybe, it would be cool to tap GitHub to see the demo project developed by one of our iPhone developers at Space-O Technologies – reliable iPhone App Development company.

    This page was last edited on January 11th, 2021, at 3:08.

Author Bio

Hitesh Trivedi

Hitesh Trivedi

Designation: iOS Team Lead

Hitesh Trivedi is an iOS Team Lead at Space-O Technologies. He has over 9 years of experience in iOS app development. He has guided to develop over 100 iPhone apps with unique features and functionalities. He has special expertise in Swift and Objective-C.

 
 

Have an App Idea?

Get your free consultation now

One thought on “How to Create a UICollectionView Controller in iOS Swift?

  1. passiondroid

    This post is more for the experienced iOS developers and not for beginners. After step 5 (Now, integrate Delegate and DataSource in app) it becomes unclear where and how to add those classes and what are those classes used for. I would appreciate a little more effort in these articles to be written for beginners.

    reply

Leave a Reply

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