iOS

Working with UITableView in Xcode 5 Using Storyboard


When we first started the iOS programming course, we wrote a tutorial about UITableView and showed you how to create a simple table app using UITableView. This is one of our most popular tutorials. However, you may find it no longer works in Xcode 5. The latest version of Xcode promotes the use of Storyboard over Interface Builder. Storyboard is no longer an option when creating a new Xcode project. It’s the default. This is one of the reasons why you couldn’t follow the steps in the UITableView tutorial to create the app.

Anyway, we decide to completely update the table view tutorial for Xcode 5 and iOS 7. And here you are.

Enter the UITableView tutorial.

First, what’s a Table View in iPhone app? Table view is one of the common UI elements in iOS apps. Most apps, in some ways, make use of Table View to display list of data. The best example is the built-in Phone app. Your contacts are displayed in a table view. Another example is the Mail app. It uses Table View to display your mail boxes and emails. Not only designed for showing textual data, Table View allows you to present the data in the form of images. The YouTube and Airbnb apps are great examples for the usage.


Sample UITableView

Creating a SimpleTable Project

With an idea of table view, let’s get our hands dirty and create a simple app. Don’t just read the tutorial if you’re serious about learning iOS programming. Stop reading, open your Xcode and code! This is the best way to study programming.

Once launched Xcode, create a new project using the “Single View application” temple.

Xcode Project Template Selection

Click “Next” to continue. Again, fill in all the required options for the Xcode project:

Product Name: SimpleTable – This is the name of your app.
Company Identifier: com.appcoda – It’s actually the domain name written the other way round. If you have a domain, you can use your own domain name. Otherwise, you may use mine or just fill in “edu.self”.
Class Prefix: SimpleTable – Xcode uses the class prefix to name the class automatically. In future, you may choose your own prefix or even leave it blank. But for this project, let’s keep it simple and set it to “SimpleTable”.
Device Family: iPhone – Just use “iPhone” for this project.

SimpleTable Project Options

Click “Next” to continue. Xcode then asks you where you saves the “SimpleTable” project. Pick any folder (e.g. Desktop) to save your project. As before, deselect the option for Source Control. Click “Create” to continue. Simply pick a folder to save your project. As you confirm, Xcode automatically creates the “SimpleTable” project based on the options you’ve provided. The resulting screen looks like this:

Main Screen of SimpleTable Project

Designing the View

First, we’ll create the user interface and add the table view. Select Main.storyboard to switch to the Storyboard interface.

Storyboard for SimpleTable Project

In the Object Library, select the “Table View” object and drag it into the view.

Drag a Table View from Object Library and add it to the view

Drag a Table View from Object Library and add it to the view

Resize its height a little bit, so that it doesn’t cover the status bar. Your screen should look like below after inserting the table view.

Drag a table view from Object Library

Drag a table view from Object Library

Run Your App for the First Time

Before moving on, try to run your app using the Simulator. Click the “Run” button to build your app and test it.

The Simulator screen will look like this:

SimpleTable App running in the simulator

Easy, right? You already designed the table view in your app. For now, however, it doesn’t contain any data. Next up, we’ll write some code to add the table data.

Adding Table Data

Go back to the Project Navigator and select “SimpleTableViewController.h”. Append “” after “UIViewController”. Your code should look like below:

The “UITableViewDelegate” and “UITableViewDataSource” are known as protocol in Objective-C. Basically, in order to display data in Table View, we have to conform to the requirements defined in the protocols and implement all the mandatory methods.

UITableViewDelegate and UITableViewDataSource

Earlier, we’ve added the “UITableViewDelegate” and “UITableViewDataSource” protocols in the header file. It may be confusing. What’re they?

The UITableView, the actual class behind the Table View, is designed to be flexible to handle various types of data. You may display a list of countries or contact names. Or like this example, we’ll use the table view to present a list of recipes. So how do you tell UITableView the list of data to display? UITableViewDataSource is the answer. It’s the link between your data and the table view. The UITableViewDataSource protocol declares two required methods (tableView:cellForRowAtIndexPath and tableView:numberOfRowsInSection) that you have to implement. Through implementing these methods, you tell Table View how many rows to display and the data in each row.

UITableViewDelegate, on the other hand, deals with the appearance of the UITableView. Optional methods of the protocols let you manage the height of a table row, configure section headings and footers, re-order table cells, etc. We do not change any of these methods in this example. Let’s leave them for the later tutorial.

Okay, let’s continue to code the app. Select “SimpleTableViewController.m” and define an instance variable for holding the table data.

In the viewDidLoad: method, add the following code to declare the “recipes” array. We initialize an array with a list of recipes.

What is an array?

An array is a fundamental data structure in computer programming. You can think of an array as a collection of data elements. Consider the recipes array in the above code, it represents a collection of textual elements. You may visualize the array like this:

recipes array

Each of the array elements is identified or accessed by an index. An array with 10 elements will have indices from 0 to 9. That means, recipes[0] returns the first element of the “recipes” array.

In Objective C, NSArray is the class for creating and managing array. You can use NSArray to create static array for which the size is fixed. If you need a dynamic array, use NSMutableArray instead.

NSArray offers a set of factory methods to create an array object. In our code, we use “arrayWithObjects” to instantiate a NSArray object and preload it with the specific elements (e.g. Hamburger).

You can also use other built-in methods to query and manage the array. Later, we’ll call the “count” method to query the number of data elements in the array. To learn more about the usage of NSArray, you can always refer to Apple’s official document.

Finally, we have to add two datasource methods: tableView:numberOfRowsInSection and tableView:cellForRowAtIndexPath. These two methods are part of the UITableViewDataSource protocol. It’s mandatory to implement the methods when configuring a UITableView. The first method is used to inform the table view how many rows are in the section. So let’s add the below code. The count: method simply returns the number of items in the “tableData” array.

Next, we implement the other required methods.

The cellForRowAtIndexPath: method is called every time when a table row is displayed. The below illustration will give you a better understanding about how UITableView and UITableDataSource work.

How UITableView and UITableDataSource work together

How UITableView and UITableDataSource work together

Okay, let’s hit the “Run” button and try out your final app. Oops! you still got a blank app! It’s the same as before.

Why is it still blank? We’ve already written the code for generating the table data and implemented the required methods. But why the Table View isn’t shown up as expected?

There is still one thing left.

Connecting the DataSource and Delegate

Like the “Hello World” button in the first tutorial, we have to establish the connection between the Table View and the two methods we just created.

Go back to the Main.storyboard. Select the table view. Press and hold the control key on your keyboard, click the table view and drag to the “Simple Table View Controller” icon of the dock. Your screen should look like below:

Connecting Table View with its Datasource and Delegate

Connecting Table View with its Datasource and Delegate

Release both buttons and a pop-up shows both dataSource & delegate. Select “dataSource” to make a connection between the Table View and its data source. Repeat the above steps and make a connection with the delegate.

Connect dataSource and delegate

Connect dataSource and delegate

That’s it. To ensure the connections are linked properly, you can select the Table View again. In the upper part of the Utility area, you can reveal the existing connections in the “Connection Inspector” (i.e. the rightmost tab).

Show the Connections Inspector

Show the Connections Inspector

Test Your App

Finally, it’s ready to test your app. Simply hit the “Run” button and let the Simulator load your app:

Simple Table View App

Add Thumbnail to Your Table View

The table view is too plain, right? What about adding an image to each row? The iOS SDK makes it extremely easy to do this. You just need to add a line of code for inserting a thumbnail for each row.
First, download this sample image. Alternatively, you can use your own image but make sure you name it “creme_brulee.jpg”. In Project Navigator, right-click the “SimplyTable” folder and select “Add Files to SimpleTable…”.

Show the Connections Inspector
Select the image file you just downloaded and check “Copy items to destination group’s folder” checkbox. By selecting the option, the image will be copied to the project folder. Click “OK” to add the file.

Pick your image file and add to the project

Pick your image file and add to the project

Now edit the SimpleTableViewController.m. Add the following line of code in “tableView:cellForRowAtIndexPath” method and put it right before “return cell”:

Your code should look like this after editing:

The table view cell comes with a default property for showing image. The line of code simply loads the image and display it in the image area of the table cell. Now, hit the “Run” button again and your SimpleTable app should display the image in each row.

Simple Table View App

Summary

It’s simple to create a table view, right? Table view is one of the most commonly used elements in iOS programming. If you’ve followed the tutorial and build the app, you should have a basic idea about how to create the table view. I try to keep everything simple in the demo app. In reality, the table data will not be stored directly in the code. Usually, it’s loaded from file, database or somewhere else. In later tutorials, you’ll learn how to store and load the table data from a file. But before moving on, make sure you thoroughly understand how the table view works. Otherwise, go through the tutorial again.

For your complete reference, you can download the Xcode project from here.

iOS
A Beginner’s Guide to Optionals in Swift
iOS
Using iAd to Display Banner Ad in Your App
iOS
Managing SQLite Database with SwiftyDB
Subscribe To Our Newsletter

Subscribe To Our Newsletter

Get a free 7-day iOS programming course, plus weekly programming tutorials, tips and freebies.

You have Successfully Subscribed!

Shares