Simple Collection View Setup

August 4, 2018 ยท 2 minute read

1. Create a new Cocoa Touch Class file

(File > New > File… > iOS > Cocoa Touch Class). Name it (e.g. MyCollectionViewCell).

2. Make sure your code looks something like this in the MyCollectionViewCell.swift file:

import UIKit
class MyCollectionViewCell: UICollectionViewCell {

 @IBOutlet weak var myLabel: UILabel!
 }

3. Prep the Storyboard:

1. Drag a collection view onto your ViewController in storyboard and set contraints.
2. Make sure that your defaults for the Collection View in Attribute Inspector are set to:
    Items: 1
    Layout: Flow
3. Drag a label and other outlets to the collection view cell 
4. Set the cell's Identifier as "cell"
5. Hook up any and all outlets to the ones defined in your MyCollectionViewCell file, as needed.

4. Update your ViewController file to the following:

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate
{
    let reuseIdentifier = "cell"
    var tempItems = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
    
    // MARK: - UICollectionViewDataSource Protocol
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return self.tempItems.count
    }
    
    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! OverviewCollectionViewCell
        
        // use outlet in custom cell class
        cell.myLabel.text = self.tempItems[indexPath.item]
        cell.backgroundColor = UIColor.magenta
        
        return cell
    }
    
    // MARK: UICollectionViewDelegate protocol
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        // handle tap events
        print ("you've selected cell #\(indexPath.item)!")
}

This is a very basic setup so that you can get it up and running. Make any changes as needed for your project (e.g. the tempItems array). To make this super useful, add it to your code snippets!

Cheers!

Buy me a coffeeBuy me a coffee