Swift Table View with Calendar Section Headers

Mazen Kilani
Apr 15 · 3 min read

Scenario

Our app contains book records in a Core Data database. We defined one of the Book attributes as Published Date. We wish to present a table view, sectioned by Publication Year, where each section contains the books published in that specific year.

Technique

We need to use the Swift DateFormatter() and the Calendar function of the Publication Date attribute to extract the Year component. Then we need to exclude any nil Publication Date values and sort the valid records by Publication Date. When building the table view sections, we shall extract the Year component and use it as the section header for books of the same publication year.

App Model

We based the article on the AppsGym Books model app, which is published on Apple’s App Store (as 8Books). You can review the Query result of ‘Books by Publication Year’ in the app. You can also download the complete Xcode project on AppsGym.com for free.

User Interface

The model app Queries menu shows options to list of book by different user-selected criteria (author, genre, publication year, etc.). The query result table view utilises dynamic section headers (year component of Publication Date) to group related records in a mini section, by publication year, within the overall list of books.

Logic

  1. Declare the variable arrays that will contain the valid Query Books to allow section headers:

Code

The Swift code snippets below are extracts from BooksByPublicationYearTableViewController.swift

If let swift = Programming!

A collection of posts to learn or improve your Swift skills.