How to create UICollectionView in Swift – Tutorial


Introduction to UICollectionView and Swift3 

UICollectionView is control used to create grid based layouts in iOS app development. With the introduction of swift3, lot of syntax changes happened, so let us dive in to the tutorial to create UICollectionView in swift.. We will use custom UICollectionViewCell class in our tutorial.

Steps to create UICollectionView in Swift 3

Create single view application, at this moment you have 3 files. Open ViewController.swift file and create an IBOutlet for our UICollectionView (We will drag and drop UICollectionView to view in storyboard in next step )


Open Main.storyboard and drag UICollectionView to the View Conroller Scene. Connect our IBOutlet, created in last step with UICollectionView.

Create a new UICollectionViewCell class and named it DummyCell (Check-mark “Also create xib file”). Open DummyCell.xib and give it height and width as shown in the image below.

How to create UICollectionView in Swift3 - Tutorial
Create UICollectionViewCell with xib
How to create UICollectionView in Swift3 - Tutorial
Set height and with for UICollectionViewCell

Drag UILabel to DummyCell.xib  and open DummyCell.swift. Create IBOutlet for UILabel, we dragged on DummyCell.xib file.

Open DummyCell.xib and connect IBOutlet with UILabel.

Open ViewController.swift, and create UICollectionViewFlowLayout. Flowlayout is used to tell
UICollectionView following things

  • Scroll Direction
  • Item Spacing
  • line Spacing
  • Size for the cell or item

As we have UIFlowLayout created for our UICollectionView, it’s time to register nib for our UICollectionView. This tells the compiler that which xib is going to be used to create cell for UICollectionView. We will also create UICollectionViewDataSource methods/functions to populate our UICollectionView.

Complete Code for UICollectionView using Swift3

Run your code and you will see the UICollectionView with two columns.

Source code for UICollectionView in swift3:

Video Tutorial for UICollectionView in swift3