Collection View Basics

Ian Value
6 min readDec 15, 2020

A blueprint for implementing collection Views

Photo by Sigmund on Unsplash

In this stage of programming I think it’s essential to have a mental framework of how to efficiently implement and manage a collection or table view. So I broke down the parts into a simple reference guide. Managing how you handle data is crucial to being a successful developer. This guide is to serve as a quick reminder for reference until you have it mentally locked down as it were. What follows is a detailed description of the how and why. This article is mainly for storyboard but the structure can be applicable to programming your UI as well.

Step 1: Add your CollectionView to your ViewController

What we will cover:

  • Add collectionView to storyboard
  • Setting up the CollectionView in storyboard

This is a simple click and drag from your object library.

Set up your contraints.

Here we set the constraints to zero around the sides and bottom and 100 at the top.

Now in your CollectionViewCell (The little box within the collectioView) add from your object library a UIImage view to the cell. Drag in an image to your assets folder on the left side of the screen. I used a Photo by Celine Ruiz on Unsplash. Set your contraints for the imageView in relation to the view.

I added a assets group. It’s not necessary, I just like having everything seperated. The width I set to 250w and the height to 200h for the cell. The imageView is constrained to 0 across the view. In your attributes inspector add your image. This image content mode is set to aspect fill.

Congrats! Your done with step 1! Now the fun begins… lets code!

Step 2: Add Data

What we will cover:

  • Connect code to storyboard
  • Create a Model
  • Add a DataSource

OK! Here we will start adding code. But first, lets set ourselves up for success. We will use an M.V.C design pattern (Model, View, Controller). To do this we will control click on our projects main file.

Create three groups. First Controller, View, and then Model. Now that we have that done our next step is to hook up our storyboard to code. In control click your view and add a new file. This will be a cocoaTouch class file. Make sure it is of type UICollectionViewCell! We will name it Gallery. Let’s hook it up to the view. In the cell type in: @IBOutlet weak var galleryView: UIImageView!

Now here is where the magic happens! Go back to your storyboard. Click on the cell you created earlier. It’s typically best to find the cell in the document outline. In the identity inspector make the class that of type GalleryCell. Now, in the cell in the document outline control click and look for galleryImages and drag from the little circle to the imageView. It will light up. Your cooking with gas now!

Awesome! Great Job!

Now we are going to create a model for our image. You guessed it…in our Model group control click and add a new file. This time it’s a swift file. Name it Gallery.

In our Gallery swift file create a struct called, you guessed it…Gallery. Within the struct we call create a variable:

private(set) public var imageName: String

It’s private to set and public to retrieve. Here is where things get a little wonky. Stay with me here!

Create an init:

init(imageName: String) {self.imageName = imageName}

Ok, heres whats up. We set to private so the data can’t be manipulated somewhere else. However, it can be publicly retrieved by another part of our app. In init we have a type of imageName that takes a type String. In the curly braces we have self (Referring to the public private var) pointing to our perameter imageName. Self acts as a pointer to the class or struct you are working in. Its telling the compiler that when you access the variable named imageName, its coming from Gallery.imageName. Since closures can be passed around swift requires them sometimes so it can distinguish between the other variables. It sounds complicated but it oddly makes total sense once you wrap your head around it.

Lets add some data. This use case here is to simulate data coming in from a server. Create a new Group called Services. In that group create a new swift file named DataModel. I grabbed more images from unsplash and add them to the assets folder. Alternatively you could add your own images. I typed it hat on unsplash.com and this is what came up.

rNJGzjANnWA-unsplash.jpg

mariano-nocetti-8rgYg4EYfO4-unsplash.jpg

andre-furtado-uED_eXXHNuQ-unsplash.jpg

ricardo-eiras-57n5rfnSjSo-unsplash.jpg

kin-li-cBZyOeR_Rhw-unsplash.jpg

celine-ruiz-KM5LQDMTBVo-unsplash.jpg

celine-ruiz-Wxs5zGQ5Oyw-unsplash.jpg

charles-deluvio-AQRp2NH-O8k-unsplash.jpg

clarisse-meyer-d6pLNFVZt_4-unsplash.jpg

celine-ruiz-rr4bawLxOjc-unsplash.jpg

Back to coding!

In out DataModel file we will now simulate data.

Create a struct called DataModel. In that struct lets create a singleton:

static let instance = DataModel()

Now lets add data. Create a private function named images that is equal to an array. In the array we will access the Gallery in our Model group we previously created.

I renamed my images “one” thru “ten” in the assets. So it will be easier to type out:

Gallery(imageName: “one”),

and so on and so on. Here, we are grabbing the assets and placing them in an array or type Gallery.

Now add a function called getImages that returns an array of type Gallery. Since images is an array of type Gallery we can return images.

Step 3: Put it all together

What we will cover:

  • Adding our data to our view
  • Updating our cells

You’re SO CLOSE! The finish line is in sight! Let’s Go!

Navigate over to your GalleryCell in your view group. Add a function called updateViews. It will take in a parameter of type gallery. From here we will access our galleryImages outlet and place the value from our model into the image.

Now its finally time to place all of this into our ViewController. I refactored my ViewController to say GalleryVC (Control on ViewController in code, refactor, rename). Now we can add the delegates.

UICollectionViewDelegate

UICollectionViewDataSource

You can add them directly to the class or create an extension. You'll get an error…that means you did it right. Click the error and add the protocol stubs.

Example for the class option.
Example for the extension.

Now we need to tell the collectionView how many images to load. Under collectionView numberOfItemsInSection type:

DataModel.instance.getImages().count

Onto the cellForItemAt IndexPath:

We need to call a custom function from the gallery cell class. We will create a constant named cell.

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “image”, for: indexPath)

We can now safely return our cell.

if let galleryCell = cell as? GalleryCell { galleryCell.someSetupFunction()

return galleryCell

We will then return the cell.

Lets now connect our outlet to our GalleryVC to our CollectionView.

@IBOutlet weak var galleryImage: UICollectionView!

Go to your storyboard. GalleryCollection. Control Click drag from the circle to the collectionView. Now we hook up the delegates. Under ViewDiDLoad:

galleryCollection.delegate = self

galleryCollection.dataSource = self

We still have to add the reuse identifier. In storyboard with our cell selected go to the attributes inspector and type in image. You may have to also go into your size inspector and where it says “estimate size” set it to none.

That is the basics of how to set up a collectionView. From here we could round the corners, change the flow layout or add more objects.

Thats it for this one! Comment below if you have some suggestions or something you are interested in learning about.

--

--