Working with UITableView in Xcode 5 Using Storyboard

108 Flares 108 Flares ×

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

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

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

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

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:

1
2
3
4
5
#import <UIKit/UIKit.h>

@interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@end

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.

1
2
3
4
@implementation SimpleTableViewController
{
    NSArray *recipes;
}

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

1
2
3
4
5
6
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Initialize table data
    recipes = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];
}

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.

1
2
3
4
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [recipes count];
}

Next, we implement the other required methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    return cell;
}

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”:

1
cell.imageView.image = [UIImage imageNamed:@"creme_brelee.jpg"];

Your code should look like this after editing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
   
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
   
    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    cell.imageView.image = [UIImage imageNamed:@"creme_brelee.jpg"];
   
    return cell;
}

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.

You May Like These:

Get Free Chapters of Our AppCoda Book

Learn iOS 7 Programming from Scratch

The Learn iOS 7 Programming from Scratch is a 400-page eBook written for beginners with little or even no programming experience. It is based on the tutorials of our popular programming course. The book starts with the basics and walks you through the process to create iOS apps using iOS 7 SDK and Xcode 5. Want to learn more? Check it out here and get two free chapters.


Build Your Own Game and Monetize on the Side

Learn how to develop your first iOS game and make money on the side. The starter kit will come with full source code of a memory game for both iPhone and iPad, as well as, a complete guide to explain how the code works. Check out the starter kit to learn more.


  • Neil Giarratana

    Great tutorial but found one bug. In the third code snippet, the data is assigned to tableData but I think it’s supposed to be recipes instead (which is consistent with the sample code that can be downloaded). An error comes back with the following:

    “Use of undeclared identifier ‘tableData’”

    Replacing tableData with recipes makes all ok.

    • http://www.simonblog.com Simon Ng

      Neil, thanks for pointing it out! It’s now fixed.

  • matheusvill

    I noticed that a constraint on the TableView is missing which is necessary to work when dragging until the end of the list.

  • Evan30

    great tutorial, but i like to ask a little question please…. What if i want the datasource to be fetch informations from twitter or youtube, what what i do.. And another one, i want to embed their search bar to an app.
    Thanks…

  • amit

    i am doing every thing that tutorial said but i am unable to see data source & delegate when i drag

    • Eric Sebastien Dechaux

      drag it the other way around, from the table view to the table view controller (yellow icon at the bottom)

    • Jonathan Groves

      Did you add a UITableView like the instructions say? Or did you drag a UITableViewController?

  • vanylapep

    checking if the cell is nil is a pretty old way of doings.. I don’t need that’s needed anymore with iOS7 ..

    • Jonathan Groves

      NSArray objects have to be terminated with nil. Refer to the NSArray Class Reference provided by Apple.

  • vanylapep

    Also, can you provide a tutorial where in the table view cell, we have a button that triggers an action. Like for example a “like this” button.

  • Ambitious Kid

    Great tutorial thus far, but I’m stuck at the array part of it…
    I understand that we have to add 2 datasource methods, but I don’t know where I need to put the code for the tableView:numberOfRowsInSection & tableView:cellForRowAtIndexPath at…

    • Eric Sebastien Dechaux

      In SimpleTableViewController.m add them just after:

      - (void)didReceiveMemoryWarning
      {
      [super didReceiveMemoryWarning];
      // Dispose of any resources that can be recreated.
      }

  • Pingback: UITableView en Xcode 5 Usando Storyboard @appcodamobile | Startup Methodology

  • Eric

    Hi There, I have a problem when I double click on Main.storyboard, it is opening Table View Controller Scene by default and I can not get rid of it. I tried to drag the Table View Controller on the view but then I have both and of course when I run the app it is empty and I don’t see the lines… Any Idea?

    • Eric

      sorry I meant to say it is opening View Controller Scene by default…

      • Eric

        ok I figured it out by myself ;) I had to move the arrow to point to the Table View Controller instead of the View Controller…

  • Peter

    Hello, thanks for the great tut. I have one “simple” question, its just to understand how the xcode project works. following example: if i follow the mentioned steps, everything works fine. what i made for tests was, removing the viewcontroller and and a new one. after this, i made the same connections in interface builder as in tutorial (datasource,delegate) but what i get is following error message “unrecognized selector sent to instance”
    ….

    2014-02-05 09:45:48.896
    ViewControllerTest[32618:70b] -[UIViewController
    tableView:numberOfRowsInSection:]: unrecognized selector sent to instance
    0x8a575c0

    2014-02-05 09:45:48.899
    ViewControllerTest[32618:70b] *** Terminating app due to uncaught exception
    ‘NSInvalidArgumentException’, reason: ‘-[UIViewController
    tableView:numberOfRowsInSection:]: unrecognized selector sent to instance
    0x8a575c0′

    Only if i create a new project the error will dissapear, but i’m sure the problem can be solved. for me it looks like, the connection between the controller and the code do not work.
    Any hints? Thanks in advance

    • http://mindhyve.com Shawn Frank

      did you add this to your header files ? If you can put your project
      somewhere online so I can look at it, it would be nice.

      • Peter

        the solution is very easy. after i removed the view controller , the new view controller i added to the storyboard was not linked to my class name. i had only the choose my class name at custom class setting..thats it….

        • Jonathan Groves

          You didn’t need to add a new view controller to the storyboard – Simon’s instructions were clearly to add a table view, not a table view controller…

          • MK

            It worked perfectly. Thanks Peter-

        • Pradip

          Hi Peter,

          I am facing same issue. Can you please explore more about this??I have used table view only not view controller..not able to see data and getting same error which u were getting

  • Sherwyn Goh

    Hi there,

    At the storyboard, I can’t seem to drag the table view into the main view, it shrinks down into an icon when I try. I believe its because of the format? Its prepared to receive only a regular view controller, not a table view controller? thanks in advance

    • Jonathan Groves

      It didn’t say to drag a table view controller, but to drag a table view…

  • Guest

    Hi, I can’t drag the tableview controller onto the view that is initially there in the storyboard, can you help? Thanks !

    • Jonathan Groves

      The instructions say “In the Object Library, select the “Table View” object and drag it into the view.” Table View, – not Table View Controller…

  • Yung-chung Lin

    It seems I did every step in the tutorial, but I still could not get it working.

    My Xcode is Version 5.0.2 (5A3005)

  • Mohamed Othman

    sorry i get lost can u add the whole code at the end

    • http://www.simonblog.com Simon Ng

      You can find the download link at the end of the article. It’s already there.

  • Roger

    Hi Simon,

    Thanks for your great tutorial!
    I’m wondering why you don’t simply use a UITableViewController instead of adding the table view to a UIViewController&implementing all the protocols manually? Is there a good reason or specific scenarios that we can’t use UITableViewController?

    Cheers~

  • Erick Alingcastre

    When I followed this tutorial, I am getting an error on the tableview implementation file. On the implementation statement, it comes up with an error message that says: “Method ‘tableView: cellForRowIndexPath:’ in Protocol not implemented”. What would cause this error?

    • Ian Paterson

      make sure that you have the syntax correct, I was having this issue until i realized i had a lower case v where i needed an uppercase V, just check the selected error area and you should find where you’ve messed up

  • Antwon L.

    Hey Simon, thanks for the great tutorial on the UITableView in xcode5. I really like how the tutorial gives instructions for each individual step so even the most inexperienced coder can follow the tutorial. When I first followed the tutorial, I initially got errors on the program, but I later found they were just my typos!

    However, I noticed that when I ran the finished app on the “iphone retina 3.5-inch” emulator and scrolled down to the lowermost part of the table, the last two items, the “Angry Birds Cake” and the “Ham and Cheese Panini”, were cut off. This problem doesn’t appear in the “iphone retina 4.0-inch” emulators though. Could it have something to do with the way the emulator is set up? Is the simple table app only meant for 4.0 inch iphones?

    Thanks

    • http://www.simonblog.com Simon Ng

      The tutorial doesn’t cater for both 3.5 and 4 inch screens. The focus is to give a basic idea of UITableView. In order to support both screen resolutions, one easy way is to use Table View Controller in Storyboard. The table view controller automatically handles different screen resolutions.

  • Nick Jones

    I just can’t get this to work. I’ve added all the requisite code to “SimpleTableViewController.m” but I can’t get the data to load into the table. I’ve control+dragged to the icon in the dock and selected “dataSource” and “delegate” as instructed but my table still shows up empty when I run the app.

    • DoctorCobweb

      i got hung up also on this. have you made sure that your table view controller is using the custom SimpleTableViewController? check it by clicking on the storyboard file, then on the yellow circle icon in the graphical display & checking out the Identity Inspector section on the right hand side.

      in the Custom Class section you need to select your custom controller ‘SimpleTableViewController’.

      hopefully this helps.

      • Nick Jones

        Actually it turns out that I had not built the UI correctly. I added a “Simple Table View Controller” to the storyboard instead of just a table view. Once I figured this out it started working like a champ.

  • Jacky

    As a beginner, I dont know why the code – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    Can you explane more detail for the required mothods?

    • DoctorCobweb

      this method is responsible for configuring the data needed for each cell in your tableView. you are given the indexPath argument which identifies the cell you are going to configure in the method body.

      and in the method body you do such things like 1) add text to the cell 2) add an image to the cell …etc.

      once you’re done configuring that cell, for the given indexPath, you return the cell (which is of type UITableViewCell), which allows the cell to be rendered/displayed.

      it helps to know that this method is called multiple times! in fact, you know exactly how many times it will be called by counting how many rows are currently being displayed onscreen in the simulator. as you scroll down and checkout more rows, this method will be called again and again, for each new row being displayed.

  • Pingback: Week 3 Reflection | m&m

  • Pingback: Week 4 Reflection | m&m

  • dylan

    I connected the table view to the data source and the delegate but when i run the app the simulator is just a black screen and it then takes me to xcode where the debug section has popped up. On the left of the debug area it has self= and underneath, recipe=. On the right side it says (lldb). any ideas on what I’m doing wrong? any help would be appreciated

  • Shaun Almond

    After I connected the TableView to my two methods my table view was still blank lines…. and I missing something?

    Also, in the very beginning whenever I tried to drag “TableView” from the objects into the existing view it wouldn’t let me. I had to drop the table view on the storyboard next to the default one, and then delete that one. Could that be part of my problem?

  • sunflowerflow

    great tutorial, helps me a lot!

  • gowtham

    i tried but it was getting error undeclared identifier tableView

  • http://justcast.heroku.com/ Josh Chen

    In the Airbnb app, in each of the table cell, it can swipe to left and right to view more pictures. Do they use UIPageViewController for it? Do you know any library can achieve it? Thank you

  • Jessy Catterwaul

    Says “temple”, not “template”.

  • Daniel Billingham

    Good stuff. As a complete beginner it took a couple of goes, but i got there in the end. Thanks for the post.

  • sajinseethi

    How can I get the item from the selected cell on to a variable ?

  • Ang

    where do you put the arrays??? help asap

  • Pingback: 「iOS TableViewのセルをカスタム – SavadorFuda’s Tech Blog」をメモ | ウェブシェフ(uzziy)

  • Nitin Nikam

    Great,,,,,,
    Very useful… very helpfull

  • kunoir

    Not working in Xcode 5.1.1. Anyone else having issues?

  • http://www.richardjburton.com/ Richard Burton

    This is not a tutorial for UITableView. It’s a (great) tutorial for UITableViewController. Please change the title :)

    • http://www.appcoda.com/ Simon Ng

      What a great feedback! Thanks Richard :)

  • Ruben Martinez Jr.

    Thanks for this! I looked at dozens of tutorials and yours was the only up to date and as well explained!

108 Flares Twitter 23 Facebook 73 Google+ 9 LinkedIn 3 108 Flares ×