UICollectionView with Section in Swift (XCODE)

In this tutorial I am going to create CollectionView with 3 Sections in Swift Programming language. This code can be used to develop your iOS application

(1) First create single view application in XCODE and drag and drop the UIViewController from Object Library into the default ViewController which you find in Main.storyboard file
CollectionView Section

(2) Select the rectangle inside the Collection View. In Attribute Inspector, you can name the Identifier as “cell”

UICollectionView Cell

(3) Now you can add the following code to ViewController.swift

Code analysis

  • Line 3: UICollectionViewDelegate and UICollectionViewDataSource Protocols have been implemented
  • Line 18: collectionView(_:numberOfItemsInSection:) says number of items in the collection
  • Line 22: collectionView(_:cellForItemAt:) method is used to create the cell

When you run the above code you can have the following screen in your simulator. We have not created sections so far

(4) You can add following method to define 3 sections

(5) To change the the colors of each section I am going to modify the following method

Finally you can have the following screen with 3 sections

How to change the number of Items in the section

Now we have done the basic code to make the Collection View with section. In this example you have the same number of items in each section. If you want to change the number of items for each section you can use the following code

Now you can have the following screen with different number of items

How to add section headers

Add the Collection Reusable View to UICollection View Controller
Enable the Section Header by selecting the Collection View controller
Enable Section Header