Your First Table View (I): The Basics - Digital Leaves
2370
page-template-default,page,page-id-2370,qode-social-login-1.0,qode-restaurant-1.0,ajax_fade,page_not_loaded,,select-theme-ver-4.1,wpb-js-composer js-comp-ver-5.2,vc_responsive

Digital Leaves. Your First Table View (UITableView). Learn Swift and iOS Programming, easy and fun.In this tutorial, we are going to learn everything about Table View (UITableView) and how to build awesome user interfaces with them. Table views are one of the most used and well-known UI control in iOS. You can find them in most apps from Apple, and in many third party apps as well.

The interface of a table view, and the different ways we interact with it has become a standard. Most users expect to be able to perform certain operations with them, like delete items by swapping right-to-left. If your view includes information that needs to be refreshed, users will intuitively pull to refresh from the screen’s top.

However, let’s start with the basics. Let’s learn about the data source of a table view and how it shows information.

Structure of a Table View

A table view is organized in sections. There might be as many sections as you need in it. Each section has a variable number of items displayed in cells. There are some predefined types of cells, but most of the times you will want to create your own custom cells.

Each section has also a header and a footer, that you can completely customize also.

Then, to reference items (cells) in a table view, we use “Index Paths” (IndexPath). An Index Path is a pair of values <section, row>. The first one specifies the section of the cell, and the second one the row inside that section. Observe that both numbers start at zero, like the indexes of an array. Thus, an IndexPath of <2, 1> refers to the second row of the third section.

The table view does not own the data used to display its cells. This data, and the behavior that dictates how the information is displayed and reacts to user interaction, relies on the Data Source and Delegate of the table respectively. Let’s know more about them.

Data Sources

A table view relies on a “Data Source” entity to get the information that needs to be displayed. This entity is usually the view controller containing the table view. You can think on this interaction as the table view “asking” the data source questions about how to display its elements. Most importantly, this information is required only when it’s needed (when the items are going to be drawn or refreshed):

First, the table asks its Data Source how many sections are in the UITableView. Usually, most tables will only have one section.

Next, the table asks the Data Source how many items are in the first section.

Then, for every item in that section, the data source returns a representation of the cell that will contain this item.

Finally, as the user scrolls up and down the table, it asks its Data Source about the sections and cells that are going to be displayed. This process continues as long as the table is visible.

Delegates

Just as a table view has a data source, it also has a delegate. The delegate of a table view dictates the behavior of the table during its lifecycle. Overall, it controls from how are cells displayed to the edition operations that can be performed (deletions, editions, moving cells…).

Most of the times, you will use the delegate to define the behavior when cells are selected (i.e: clicked) or highlighted. Also, another common use of the delegate is adding the ability to remove items from the table. A typical scenario is “if someone clicks on any cell, take the user to a screen with details for the item in that cell”.

Usually, the entity that takes the role of Data Source for the UITableView acts also as its Delegate. Commonly too, this entity is the view controller that contains the table.

Later, we’ll see how to use the delegate to define different interactions for our tables. But for now, let’s talk about our sample application.

Our Sample Application

Our sample application is a very simple app that will display a list of animals. If the user clicks on a cell, we will transition to another screen where we will show details of that animal.

Creating Our First Table View

First, open Xcode and create a new project. Let’s call this project “My First Table View”. Choose “Single View Application”.

You will notice that there’s a kind of view controller called “Table View Controller”. This type of view controller has been specifically designed to act as the controller of a UITableView. Thus, it already contains a table view and has been set as the data source and data table for that table.

However, this type of controller has some important limitations. As an example, you cannot add other views around the table. It might be useful for putting together a screen where you are certain that the only visible element is -and will forever be- the table view.

Therefore, I recommend always using a normal view controller and properly configuring it to become the controller of the UITableView. So first open the main storyboard and add a table view. Then expand it to the edges of the screen and pin it there like the figure below shows:

Digital Leaves. Your First Table View. Learn Swift and Build Awesome Apps.

Adding Cells To Our Table View

After we properly dimension it, we need to define the cells for the table. A table might have several “templates” for the cells that are going to be displayed. Usually, though, you will have only one type of cell.

These templates are nothing more than views that define how the information is displayed. There are some predefined templates for simple cells containing a title and maybe a subtitle (like “Basic”, “Right Detail”, etc). For serious applications, though, you will probably be defining your own custom cells for greater flexibility. We’ll learn how to do this later.

For now, however, the simplest way of adding a cell is just simply by dragging and dropping it inside the table. Locate the “Table View Cell” element in the Object Library in the Utilities panel. Then, drag and drop it inside the table. You will see that a cell appears below a “Prototype Cells” text.

Next, set an identifier for the cell. Every cell type or prototype you define must have an identifier to reference its class in source code later. This is important if we want to be able to instantiate our cells at all. Set the cell’s identifier to “myTableViewCell”.

Finally, go to the “Attributes inspector” and set the style to “Basic”. You will notice how a “Title” label appears in the cell.

Setting the Data Source and Delegate for the Table

Next we need to set our view controller as the delegate and data source for the table view.

In order to do that, while holding the Ctrl key, click on the table view and drag & drop to the View Controller icon. This icon is the yellow circle with a white square on the top bar of the view controller in the storyboard.

If you have never set outlets, actions or delegate/data source entities, you should probably have a look at this tutorial.

Digital Leaves. Your First Table View. Learn Swift and Build Awesome Apps.

It will be useful too to add an outlet for the table view. Add that now and call the outlet property “tableView”.

Embedding The View Controller in a Navigation Controller

Our table view is ready. There’s just one last step that we need to accomplish. When our users click on an item, we want to segue to a new view controller showing the details for that animal.

In order to do that, we need to add a navigation view controller to manage the navigation between them. Go to the storyboard, click on the view controller’s icon (the yellow one at the left of the status bar of the view controller). Then select in the menu: Editor > Embed In > Navigation Controller. The navigation view controller will appear and wrap the view controller, as depicted in the image below.
Your First Table View. Digital Leaves. Learn Swift and Build Awesome iOS Apps. Free and Ads Free.

Now that we have that in place, we can start adding functionality to our view controller.

Setting Our Data Source Methods

The first thing we need to do is set our View Controller as the Data Source and Delegate of the table. Even though we did that before in the storyboard, we will explicitly specify that in our class definition:

None of the UITableViewDelegate methods are mandatory (meaning, we don’t have to implement them), but we need to comply at least with two methods for the UITableViewDataSource protocol:

tableView:numberOfRowsInSection:

This method specifies how many rows are in a given section. First, we should define numberOfSections:, but the default implementation returns 1. Thus, we can safely ignore this method as we only want one section.

In our one and only section, we will display as many rows as animals. First thing, then, is defining our array of animals:

Now we can easily define the number of rows method as the count for the array:

We will add an image for every animal in the project’s media asset archive. Then, we will be able to show a nice picture in the description of every animal. You can get the full source code with the assets from the github repository.

tableView:cellForRowAt:

Next, we will define the method that tells the table view what cell needs to be displayed for every row. This method has to return an instance of UITableViewCell (a cell), either one of the default templates or a custom one.

First, we will start with the default cell we added to the table view before. Later, we’ll learn to create and add a custom cell. For now, all we need to do is getting a cell with this “Basic”default template, set the title to the name of the animal and return that cell.

It’s essential to understand the matching between the data between the Data Source entity and the representation at the table. In this case, each row will be one item in the “animals” array. Thus, given that there’s only one section, the cell for Index Path (0, x) will be the item “x” in the array. Remember that the first element starts at zero (corresponding to Index Path (0,0)).

As a result, we will define our tableView:cellForRowAt: as follows:

Running Our First Table View App

Finally, it’s time to run our App. Click the play button at the top bar. If everything went well, you should see a list populated with the list of animals. Yay!

Congratulations. You just built your first application with a table view.

Where to go from here

This is the first of a series of tutorials focused in helping you master tables (UITableView) in Swift, one of the most used and well-known UI controls in iOS. In this episode, we learned the basic concepts of a Table View, how to add them, the concepts of Data Source and Delegate, and how to properly populate them.

In the next episode, we’ll learn how add functionality when a user clicks on a cell, and how to design and define custom cells to build more appealing tables for our apps.

 

 

Before you continue...

Hi there! I created the Digital Tips List, the newsletter for Swift and iOS developers, to share my knowledge with you.


It features exclusive weekly tutorials on Swift and iOS development, Swift code snippets and the Digital Tip of the week.


Besides, If you join the list you'll receive the eBook: "Your First iOS App", that will teach you how to build your first iOS App in less than an hour with no prior Swift or iOS knowledge.

I hate spam, and I promise I'll keep your email address safe.