Member-only story

Building a Dual-Column UICollectionView Using SnapKit in Swift

Jerry PM
4 min readOct 14, 2024

--

Use One CollectionView with Two Different Data

Source: Author

When creating an iOS application that needs to present data in a dynamic and visually structured format, UICollectionView is often the go-to solution. This article will walk you through how to build a simple UICollectionView that displays two sets of data side by side — popular stocks on the left and popular funds on the right. We’ll also use SnapKit for concise Auto Layout management.

Overview of the Project

In this project, we are building a custom CollectionSideController, a UIViewController subclass that contains a UICollectionView. The collection view will present two columns: one for stocks and one for funds. The data is divided into two arrays: popularStocks and popularFunds. These arrays will populate the cells of the collection view.

Project Structure

  • DataArray struct: Stores the stock and fund data.
  • CollectionSideController: The main view controller that manages the collection view and its layout.
  • PopularCell: A custom collection view cell for displaying the data.

Prerequisites

Before diving into the code, ensure that you have installed SnapKit, a popular library for defining Auto Layout constraints programmatically in a more readable manner. You can add SnapKit to your project using CocoaPods, Carthage, or Swift Package Manager.

pod 'SnapKit'

Once SnapKit is added to your project, you’re ready to go.

Step-by-Step Implementation

1. Define the Data Model

We start by creating a simple struct, DataArray, which will hold the stock and fund data:

struct DataArray {
var popularStocks: [String]?
var popularFunds: [String]?
}

2. Set Up the View Controller

Next, we create a subclass of UIViewController, called CollectionSideController. This controller manages the UICollectionView and provides it with data.

class CollectionSideController…

--

--

No responses yet

Write a response