Create UICollectionView Programmatically in Swift

In this tutorial, you will learn how to create a UICollectionView programmatically in Swift. You will learn how to create a new UICollectionView withย UICollectionViewFlowLayout and will learn how to make it display a few cells. You will also learn how to make your UIViewController conform to a UICollectionViewDelagate to handle events when user taps on a cell.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

1. Create UICollectionView Programmatically

To create a UICollectionView programmatically, I will create a new instance of UICollectionView by giving it a UICollectionViewFlowLayout as a parameter.

class MyViewController : UIViewController {
    var myCollectionView:UICollectionView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let view = UIView()
        view.backgroundColor = .white
        
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 60, height: 60)
        
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

        myCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        myCollectionView?.backgroundColor = UIColor.white

        view.addSubview(myCollectionView ?? UICollectionView())
        
        self.view = view
    }
}

The above collection view will not display any items however. To make UICollectionView display items, we will need to make it conform to a UICollectionViewDataSource protocol.

2. Conform to UICollectionViewDataSource Protocol

To make the UICollectionView display items, you will need to make it conform to a UICollectionViewDataSource protocol. Update the code snippet below by adding the following two lines of code before right after creating a new instance of UICollectionView.

myCollectionView?.dataSource = self
myCollectionView?.delegate = self

Next, create the following extension and implement the two required functions.

extension MyViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 9
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
        myCell.backgroundColor = UIColor.blue
        return myCell
    }
}

Notice, that the first function returns a hard-coded number of items that should be displayed in the view. The number of items you return from this function will tell the UICollectionView how many cells to display.

The next function will create return a new cell. You can customize each cell and add other UI elements to it as subviews.

Let’s put these two code snippets together into a complete code example.

Complete Code Example in Xcode Playground

Below is a complete code example in the Xcode playground. You should be able to reuse this code in a regular Xcode project just fine.

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    var myCollectionView:UICollectionView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let view = UIView()
        view.backgroundColor = .white
        
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 60, height: 60)
        
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

        myCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        myCollectionView?.backgroundColor = UIColor.white
        
        myCollectionView?.dataSource = self
        myCollectionView?.delegate = self
 
        view.addSubview(myCollectionView ?? UICollectionView())
        
        self.view = view
    }
}

extension MyViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 9 // How many cells to display
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
        myCell.backgroundColor = UIColor.blue
        return myCell
    }
}

extension MyViewController: UICollectionViewDelegate {
 
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       print("User tapped on item \(indexPath.row)")
    }
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

If you copy, paste and run this code in Xcode playground, you should get the following result.

UICollectionView in Swift Programmatically

I hope this tutorial was of some aid to you. Have a look at other Swift tutorial on this website. It has many more interesting ones.

Happy coding ๐Ÿ™‹๐Ÿปโ€โ™‚๏ธ!

Leave a Reply

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