iPhone SDK Articles

Tuesday, January 13, 2009

UITableView - Creating a Simple Table View


If you want to display a list of items in your app, then UITableView object is your answer. The object makes it really easy to display a list of items. In this tutorial, you will learn how to set up a simple table view. Click on "Read more" to get started.
Introduction
In most cases, the requirement is to select an item from the list displayed and then load the details of the selected item in a detail view. UITableView is only responsible for the list of items it displays, the navigation that happens between the list of items and the detail view is handled by the UINavigationController. So the table view always works with the navigation controller and viceversa. This is how the final app looks like

Creating the project
Create a new XCode project by clicking on File -> New Project -> (Under iPhone OS) select "Navigation-Based Application", give it a name and save the project. I have named my project "TableView". The project template "Navigation-Based Application" will give you a navigation controller and a table view tied together, so you do not have to set it up manually.

Data Source
Since we want to display not one or two but a list of items in the table view, we need some kind of a data source to hold our data and something which we can pass it on to the table view so it can use it. This data source can come from anywhere XML Files, Databases, or an array. To learn how to use SQL Lite databases read my SQL Lite tutorial series here. To keep this tutorial simple, I will choose a NSMutableArray as the data source for the table view. You can fill this array from XML files or SQLLite database. The array will be populated with string objects and not custom objects to keep the tutorial less confusing. Read my SQL Lite tutorial series to understand how to use custom objects with the table view.

The first thing to do is to build the data source, populate it with the items we need to display in the table view. Let's build our data source in viewDidLoad method of the RootViewController which is called when the view is loaded. This is how the header file and viewDidLoad method in the implementation file looks like

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {

NSMutableArray *listOfItems;
}

@end

//viewDidLoad method declared in RootViewController.m
- (void)viewDidLoad {
[super viewDidLoad];

//Initialize the array.
listOfItems = [[NSMutableArray alloc] init];

//Add items
[listOfItems addObject:@"Iceland"];
[listOfItems addObject:@"Greenland"];
[listOfItems addObject:@"Switzerland"];
[listOfItems addObject:@"Norway"];
[listOfItems addObject:@"New Zealand"];
[listOfItems addObject:@"Greece"];
[listOfItems addObject:@"Rome"];
[listOfItems addObject:@"Ireland"];

//Set the title
self.navigationItem.title = @"Countries";
}

//dealloc method declared in RootViewController.m
- (void)dealloc {

[listOfItems release];
[super dealloc];
}

Array "listOfItems" is declared in RootViewController.h file and is of type NSMutableArray, it is also released in the dealloc method as shown above.

In viewDidLoad method, we allocate memory and initialize the array and add 8 objects to it. The view of the navigation bar is set to "Countries". Now somehow we need to tell the table view to display the items in the array.

Customize the number of rows in the table view
The first thing we have to do is, tell the table view how many rows it should expect and this is done in tableView:numberOfRowsInSection. This method returns an integer which is the number of rows that the table view will display. Since our array consists of 8 objects, we will pass the count message to the array. This is how the code looks like

//RootViewController.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listOfItems count];
}

Display data in a table cell.
Now that the table view knows how many rows to display, we need to display the actual text which goes in a table view cell. The table view is made of table rows and rows contains table cell. This is done in tableView:cellForRowAtIndexPath which is called n number of times, where n is the value returned in tableView:numberOfRowsInSection. The method provides indexPath which is of type NSIndexPath and using this we can find out the current row number the table view is going to display. This is how the code looks like

//RootViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

// Set up the cell...
NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
cell.text = cellValue;

return cell;
}

In the code above, we first initialize the cell if required. Then get the string from the array, by passing objectAtIndex method to the receiver, with the current row number. The "cellValue" is then set to the text of the cell and the cell is returned. Run your application to see the eight rows in the UITableView.

Conclusion
UITableView really makes it easy to display list of items, by configuring few simple methods. I hope this tutorial helped you in getting started. I know this tutorial is really simple but this way I really get to concentrate on one problem at a time. In my next tutorial,I will show you how to load a detail view and pass data to it.

Happy Programming,
iPhone SDK Articles



Attachments
Suggested Readings


11 comments:

Anonymous said...

Thanks for posting this tutorial!

I've read so many tutorials on how to handle a UITableView but they all just say like "type this and it'll do that".
You go along every function and explain it.

So great work, thanks a lot!

Anonymous said...

Thank you! I have worked through several other tutorials, but after this one I finally understand!

Thiago said...

Thanks for posting, very easy to follow and it worked without any glitches..

just a quick question, shouldn't the cellValue string be released at the enf of the cellForRowAtIndexPath function?

Now on to part II! :)

Thiago

iPhone SDK Articles said...

@Thiago

Good to know the tutorials helped you.

Yes, you are right "cellValue" should be released. I will update the code. Good catch :)

Happy Programming,
iPhone SDK Articles

Julien said...

This is a great tutorial. Now, what would I do if I wanted to load a second view? I know it would involve doing something with the interface builder, but what exactly?

Thanks

iPhone SDK Articles said...

@Julien I think this tutorial http://www.iphonesdkarticles.com/2009/01/uitableview-loading-detail-view.html answers your question.

Please let me know if I can be of any more help.

Happy Programming,
iPhone SDK Articles

Jan Verhulst said...

BIg big thanks for these tutorials! You're great man! Really good explanation.

I'm doing this research for school, and you're really helping me :)

Michael said...

Excellent tutorial: my only quibbles are that you could use arrayWithObjects to shorten the section where you add items, and I believe that Rome is just a city, not a country :-)

Anonymous said...

Hi

Thanks. But you left this bit out of your tutorial (which I found in the source file). Perhaps you should include it in the above tutorial so that there are no errors.

// Set up the cell...
NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
cell.text = cellValue;

return cell;

iPhone SDK Articles said...

@Michael

that is a big oops, I will change it as soon as possible.

Happy Programming,
iPhone SDK Articles

Anonymous said...

Hey,

in listofitem i have added 15 items

But while loading it displays only first 10 items

what the problem..

help me pls..