【Swift・UIKit】 Creating a CollectionView Programmatically

Simple Apps

In this article, I’ve implemented a CollectionView entirely in code, which is a common component in Swift. I hope it’s helpful for you!

What is a CollectionView?

A CollectionView is used to display many items in a grid-like format, similar to a panel. It allows you to arrange items both vertically and horizontally.

Implementation

Here’s what I’ve implemented:

Setting Up CollectionView in Code

This post will focus on implementing CollectionView purely with code. For detailed explanations on previous setups, please refer to this article:

Step 1: Define Screen Size

Before creating the ViewController, we’ll define the screen size.

let screenSize: CGSize = 
CGSize(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)

Step 2: Create and Register the CollectionView

Next, we create the CollectionView and register it.

let collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.width), collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.white
    collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
    return collectionView
}()

Step 3: Create the Cell (CollectionViewCell)

Now, let’s create a separate file for the cell, where we’ll define its details. In this case, we’ll just set a simple border for each cell.

class CollectionViewCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        layer.borderColor = UIColor.darkGray.cgColor
        layer.borderWidth = 3.0
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Step 4: Set DataSource and Delegate

Don’t forget to set the dataSource and delegate for the CollectionView.

collectionView.dataSource = self
collectionView.delegate = self

Also, be sure to declare these protocols in the ViewController class:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

Step 5: Implement Required Functions

There are two essential functions you need to implement:

  1. Number of Cells
    This function sets the number of cells in the CollectionView.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 4
}
  1. Cell Content
    This function defines the content of each cell.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
    return cell
}

Step 6: Set Cell Size with FlowLayout

You can fine-tune the layout of the CollectionView in many ways. In this example, we’ll keep it simple and just set the cell size.

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

Step 7: Add CollectionView to the View

Finally, don’t forget to add the CollectionView to your view and disable auto-resizing constraints.

override func viewDidLoad() {
    super.viewDidLoad()
    
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(collectionView)
}

References

Final Thoughts

There are countless ways to customize CollectionView, and the possibilities are endless. I plan to keep updating this as I explore more!

Comments

Copied title and URL