Chapter 2
Creating Table View Sections and Index list with Diffable Data Source

If you'd like to show a large number of records in UITableView, you'd best rethink the approach of how to display your data. As the number of rows grows, the table view becomes unwieldy. One way to improve the user experience is to organize the data into sections. By grouping related data together, you offer a better way for users to access it.

Furthermore, you can implement an index list in the table view. An indexed table view is more or less the same as the plain-styled table view. The only difference is that it includes an index on the right side of the table view. An indexed table is very common in iOS apps. The most well-known example is the built-in Contacts app on the iPhone. By offering index scrolling, users have the ability to access a particular section of the table instantly without scrolling through each section.

Let's see how we can add sections and an index list to a simple table app.

If you have a basic understanding of the UITableView implementation using diffable data source, it's not too difficult to add sections. And to add an index list, you need to override these methods as defined in the UITableViewDiffableDataSource class:

  • tableView(_:titleForHeaderInSection:) method – returns the header titles for different sections. This method is optional if you do not prefer to assign titles to the section.
  • sectionIndexTitles(for:) method – returns the indexed titles that appear in the index list on the right side of the table view. For example, you can return an array of strings containing a value from A to Z.
  • tableView(_:sectionForSectionIndexTitle:at:) method – returns the section index that the table view should jump to when a user taps a particular index.

There is no better way to explain the implementation than showing you an example. As usual, we will build a simple app, which should give you a better idea of an index list implementation using the diffable data source approach.

A Brief Look at the Demo App

First, let's have a quick look at the demo app that we are going to build. It's a very simple app showing a list of animals in a standard table view. Instead of listing all the animals, the app groups the animals into different sections, and displays an index list for quick access. The screenshot below displays the final deliverable of the demo app.

Figure 2.1. Demo app
Figure 2.1. Demo app

To continue reading and access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.

results matching ""

    No results matching ""