Programmatic Custom CollectionView Cell Subclass in Swift 5 & Xcode 10
Using CollectionView & CollectionViewCell to create a basic custom cell, this article will show you how to subclass UICollectionView, register it to a UICollectionView, and dequeue it for re-use in the ‘cell for item’ at data source protocol method. Let’s get started.
My name is Max & I run maxcodes.io. As always, it’s nice to finally meet you.
Source Code & Video Format
Article In Video Tutorial Format — Source Code Link Is in The Video Description!
Step 1. Create a blank Xcode project and add a collectionView
- When declaring a collectionView you have to pass in a UICollectionViewLayout instance. We do this with UICollectionViewFlowLayout and we also change the scroll direction to horizontal for effect.
- when using programmatic auto layout with NSLayoutConstraint you must set translatesAutoResizingMaskIntoConstraints to false on the view you wish to constrain.
- We register a basic UICollectionViewCell and use the reuse identifier “cell”. When we use a custom cell we will come back to this line and modify it. But for now, just leave this here, we need it for basic cells in the next step. If you want more of an explanation check out my full UICollectionView course. Patience, you will be an iOS master in no time if you keep up the hard work.
Add the following code to ViewController.swift and you will be given the following output. It looks like a simple UIView with a blue background color.
Step 2 — Conform to The CollectionView Data Source and Delegate Protocols
This will break your app until you add the code in step 2 continued below.
Step 2 — Continued — Extension for CV Protocol Methods
Add the following code. This will fix your app and you will have no errors.
There are three methods here.
- sizeForItemAt — belongs to the DelegateFlowLayout protocol
- numberOfItemsInSection — belongs to DataSource
- cellForItemAt — belongs to DataSource
They do what they say. sizeForItemAt indexPath, allows us to modify the size of cells. numberOfItemsInSection allows us to tell the collection how many cv cells we want to return. cellForItemAt lets us dequeue and use cells how we want.
Step 3— Create a custom cell and register it.
First, you need to create a subclass of UICollectionViewCell. Go ahead and write all this code… Or, If you want to copy and paste this code, you can find the source code for free in the description of this YouTube video!
All we are doing is taking UICollectionViewCell and slapping a UIImageView onto the entire thing. Notice I have an image set on the imageView in the declaration. You can find free high-quality photos on Unsplash. Again, completely free.
Step 3 — Continued— Register and Cast the Cell.
Right now, if you compile, nothing happens because we are still using UICollectionViewCell in our UICollectionView. How do we use our custom cell you ask? Ahh, glad you asked, let’s revisit our cv declaration above viewDidLoad.
- Instead of registering UICollectionViewCell, how about we register CustomCell? Yes, do it!
- Make sure to cast the cell as seen in the updated screenshot of our collectionView protocol methods. Specifically cellForItemAt indexPath
- Again, the source code is here in the description if you’re lost AF.
How do we get custom data into these custom cells though?
Enter Step 4.
Step 4 — Structs & Custom Data
- Write the struct you see in this screenshot. We will only be using the image but I show you how to use an entire struct to teach you how to use more than a single default type. I do this so you can do what you want with your new knowledge after you are done with this article.
- Declare an array of data containing our CustomData instances — Notice the image literals. Again, I used Unsplash.com to get these free images.
- Notice the second title — subscribe to maxcodes boiiiii!— Ahh yes, elegant. Make sure to visit maxcodes.io to join the free newsletter haha.
Step 4 — Continued — cellForItemAtIndexPath and didSet data.
- Modify the protocol methods to utilize this custom data array. You’ll get an error.
- At the top of CustomCell, add this code. Boom errors gone and you get the output pictured in the middle.
Step 5 — Super Quick Step.
In viewDidLoad, change the height constraint to the following:
collectionView.heightAnchor.constraint(equalToConstant: view.frame.width/2).isActive = true
All I did was change the constant from view.frame.height/2 to view.frame.width/2
You’re Finished. Here are Some Resources.
Source code available (click here) in the video description of this tutorial
Become Advanced.
If you want to take your collectionView skills to the next level, check out my Build UICollectionView Apps with Swift & Xcode course with this discounted coupon link.
As always, Thank you for your continued support!
I appreciate everything from likes to students enrolling in my courses. It helps me help you!