In this Swift Tutorials : iOS PROGRAMMING WITH SWIFT TUTORIALS AND LESSONS lesson we will tell you how to createCollectionView from Scratch using Swift and Xcode (We made it in Xcode 8 using Swift 3)

Follow Along

Open Xcode > New Project and select Single View Application

In the Product Name Type : CollectionView

Click “Main StoryBoard” in the Navigator

Find Collection View in the objects library and drag it to viewController

Go to “Add New Constraints”, uncheck “Constrain to Margins” and after that set all 4 constraints spaces to 0 and click “Add 4 Constraints”

TableView

Select a Collection View in storyboard and click “Update Frames”

 

Open ViewController.swift file and add delegates to the class

after

In your StoryBoard select a Collection View object and Ctrl Drag from it to your ViewController.swift file. Create an outlet named collectionView

In your viewDidLoad() function type:

With these two lines you are telling that your ViewController will be a delegate and a dataSource of your tableView.

Now it’s time to conform to our protocols and to set up required methods.

First, let’s setup number of sections:

After that let’s create a simple collections array that stores the values that we want to display in our collectionView:

Let’s write a method to count how many items to show in our collection view.

Now we need to create a cell class that will describe how our cell will look like:

Go to File>New>File and create a new Cocoa Touch Class named MainCollectionViewCell as a subclass of UICollectionViewCell and “also create XIB file” should be cheked.

Go to size inspector and set width and height to 100.

Drag a label and center it inside the cell.

Create an outlet from MainCollectinViewCell.xib ‘s label to MainCollectionViewCell.swift file named :

Now go to ViewController in storyboard, tap on the cell and in the Attributes Inspector set identifier to “mainCollectionViewCell”

Now we are ready to setup another method in our ViewController to configure the cell:

In viewDidLoad add:

If we run it now, we will have the following result:

Collection View

Collection View

 

Great, what can be else done?

We can configure number of columns. To do this :

Run the app and you will see 2 columns.

This lesson is a part of iOS PROGRAMMING WITH SWIFT TUTORIALS AND LESSONS created by the Apps-Top.com Team. Feel free to save and share this post to social if you find this lesson useful or helpful.