Day 42 - 100 Days of Swift

2 minute read

Project 10 (part 1)

Day 42 is is the first part of the tenth project. It will be an app that displays photos of people in a collection view, along with their names, to help you remember who’s who. Today, you get the project set up, you lay out the custom cell and make a class for it, and you get the collection view data source methods implemented in a very basic way.

First, you make a new project, replace the default UIViewController in the storyboard with a UICollectionViewController, embed it in a UINavigationController and set it as the initial view controller. You add a UIImageView and a UILabel to the cell, and get them laid out:

Screenshot of storyboard showing collection view controller and cell with image and label.

You make a custom class for the UICollectionViewCell, set the cell in the storyboard to it, and add outlets for the image view and the name label:

1
2
3
4
5
6
class PersonCollectionViewCell: UICollectionViewCell {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var nameLabel: UILabel!

}

Then, in ViewController, you add the necessary UICollectionViewDataSource methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
override func collectionView(_ collectionView: UICollectionView,
                             numberOfItemsInSection section: Int) -> Int {
    return 10
}

override func collectionView(_ collectionView: UICollectionView,
                             cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PersonCell",
                                           for: indexPath) as? PersonCollectionViewCell else {
        fatalError("Unable to dequeue a PersonCollectionViewCell. Check for typos")
    }

    return cell
}

If you aren’t able to cast the dequeued collection view cell as a PersonCollectionViewCell, then you crash because it most likely means that you have a typo somewhere or that something got disconnected in the project. And that’s it for today. Here’s what it looks like so far:

Screenshot of working app in its current state.

You can find my version of this project at the end of day 42 on Github here.

Reflections

Today was real short. He spent most of the time talking through how to layout a cell, and how to make a custom class for one. And then comparing UITableViewDataSource and UICollectionViewDataSource. Big topics, I guess, but they didn’t lead to very much code being written. I’m looking forward to seeing it come together tomorrow.