Episode #385

Styling Custom Cells

Series: Making a Podcast App From Scratch

15 minutes
Published on April 5, 2019

This video is only available to subscribers. Get access to this video and 582 others.

In this episode we add our tableview cell styling to match the design, using autolayout to arrange the views and using the Xcode View Debugger to find and fix a visual glitch when using dark background cells.

Creating a View Model for our Cells

struct SearchResultViewModel {
    let artworkUrl: URL?
    let title: String
    let author: String
}

We can now use this in our cell subclass to configure the views.

// in SearchResultCell.swift
func configure(with result: SearchResultViewModel) {
    podcastTitleLabel.text = result.title
    podcastAuthorLabel.text = result.author
    // image download will come later
}

Styling the Cell

We can configure a lot of the styling in the storyboard, however we want to be able to reference the theme's color constants.

override func awakeFromNib() {
    super.awakeFromNib()

    backgroundColor = Theme.Colors.gray4
    backgroundView = UIView()
    backgroundView?.backgroundColor = Theme.Colors.gray4

    podcastTitleLabel.textColor = Theme.Colors.gray0
    podcastAuthorLabel.textColor = Theme.Colors.gray1
}

This looks good until you tap on a cell. The selected style makes the labels unreadable.

To fix this, we'll add this to the awakeFromNib() method.

    selectedBackgroundView = UIView()
    selectedBackgroundView?.backgroundColor = Theme.Colors.gray3

Configuring the Table View

For the tableView separator, we can customize the color and indentation, as well as the background color for the overall view:

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.backgroundColor = Theme.Colors.gray4
    tableView.separatorColor = Theme.Colors.gray3
    tableView.separatorInset = .zero
}

This episode uses Swift 4.2, Xcode 10.1.