Adding A UICollectionViews To A Custom UITableViewCell Xib Tutorial(Swift 4 Xcode 9.2)

aestusLabs
3 min readApr 24, 2018

--

I was surprised to learn how many stumbling points there were to implement a UICollectionView in a UITableViewCell. So I am going to a compile the plethora of sources I used into one coherent starting point.

Note: This is not a tutorial for beginners. It assumes you know about tableViews and making custom cells with xib files.

It also isn’t going to go into anything you need to do to make your collection view look good.

1. Add A UICollectionView To Your TableViewCell Xib

  1. Drag in a collection view
  2. Add Constraints
  3. Find out you can’t add CollectionViewCells to your newly added collection view.

Turns out you need a separate file to house any Collection View Cells you want to display. (When your UICollectionView is in a Xib file)

2. Add A UICollectionViewCell File And Xib To Your Project

(You Can Name It Whatever You Like)

You can do whatever you want in your CollectionViewCell Xib, for the purposes of this tutorial I’m just going to change the background colour.

Make sure you give your cell a resuableIdentifier.

3. Conforming Your TableViewCell Class To UICollectionView Data Source And Delegate Protocols

Step1: Go back to your tableViewCells Xib file.

Step 2: Show Document Outline

Step 3: Control drag from your collectionView to ‘File’s Owner’ and select dataSource and then do it again and select delegate.

Step 4: Control drag from your collectionView to your TableViewCell class and make an IBOutlet

Step 5: Conform your tableViewCell Class To UICollectionViewDelegate And UICollectionViewDataSource

  1. Add UICollectionViewDelegate and UICollectionViewDataSource To The Class Description
  2. Make the collectionView’s data source and delegate = self in awakeFromXib
  3. Add the numberOfItemsInSection function
  4. Add the cellForItemAt function
  5. Create a cell with your reuseIdentifier and downcast as your custom cell.
  6. Hit run.

It will immediately crash. We need to “register a nib or class for the identifier or connect a prototype cell in storyboard”.

5. Register Your Xib

In your tableViewCell’s awake from Nib add this line:

self.collectionView.register(UINib.init(nibName: “CollectionViewCell”, bundle: nil), forCellWithReuseIdentifier: “collectionViewID”)

Build and run again. It will work. Here is the updated tableViewCell’s code:

Troubleshooting Steps:

  • Are my identifiers assigned and correct?
  • Did I drag from my collectionView to the File’s Owner in your Xib file?

Hope this helped. Give me a clap if you like. Comment if you have issues.

Ian — aestusLabs

--

--

aestusLabs

I’m an aspiring software developer, focusing on iOS Swift development. When I solve a problem in my own app development I post a tutorial to help you out.