V2EX
UITableView
Posted in iPhone on September 20th, 2008 by Xin

I will try to explain several important concepts of UITableView in this post, UITableView was the most confusing component when I was making my first iPhone app, it took me some time to understand it so that I’m really happy to share what I’ve learned with you.

Basics

UITableView is a subclass of UIView, that means you can initialize it and add it to a UIView using addToSubview method just like other UIView subclasses.

Following code will create an empty UITableView and add it to a view named mainView:

UITableView * aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[mainView addToSubview:aTableView];

Now you’ve got an empty UITableView, but it can do nothing. For populating data and handling taps, you’ll need to set a datasource and a delegate for your UITableView. The object you’ll use for datasource and/or delegate must adopt protocol UITableViewDelegate and/or UITableViewDataSource. You don’t need to use two objects for handling the two protocols, one object is enough unless you have other reasons to use two.

Data Source

You can set an object as datasource like this:

[aTableView setDataSource:anObject];

The object acts as datasource usually needs to implement these methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

This method will tell UITableView how many sections it will have. One example of sections is in Contacts app, contacts with different family names are organized into sections by initials.

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

This method will tell UITableView what to display in section headers. In Contacts app, initials are displayed in section headers.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

This method will tell UITableView how many cells it will have per section. If you have only one section, just simple return the total number of cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

This is the most important method in datasource. After UITableView is created and has a datasource, when a cell is visible on screen, UITableView will query datasource for the cell to decide what to draw in the cell.

You have two ways to construct a cell, simple and complex.

Simple way:

This will produce a cell with a single line of text in standard font and size, as you have seen in Contacts app.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *theIdentifier = @"theIdentifier";

  // Try to recover a cell from the table view with the given identifier, this is for performance
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:theIdentifier];

  // If no cell is available, create a new one using the given identifier
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
  }

  // Fill the cell
  cell.text = [NSString stringWithString:@"Hello World"];
  return cell;
}

Complex way:

If you want to have images or labels in a cell, first you’ll need to subclass UITableViewCell, then you can draw them into a cell’s contentView. If you want to have customized backgrounds like in Twinkle, you can prepare a UIView and assign it to cell’s backgroundView.

When you have images or other customized content in contentView, you’ll usually need to use different identifiers for cells, this is different from the example in simple way. Unique identifiers usually come from data retrieved from Internet. For example, if you’re populating a UITableView with contents from RSS, you may use article ID as UITableViewCell identifier.

Below is a complete example of customized UITableViewCell, it uses a subclass ArticleCell inherits from UITableViewCell, ArticleCell has two UILabel (title, author) in properties. This example also demonstrated how to use a thread to download image from Internet and assign it to a UIImageView in UITableViewCell, you’ve seen this in two official apps: YouTube and App Store.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  Aricle * anArticle = [[articles objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

  NSString * CellIdentifier = [anArticle articleID];
  ArticleCell * cell = (ArticleCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if (cell == nil) {
    cell = [[[ArticleCell alloc] initWithFrame:CGRectMake(0,0,320,84) reuseIdentifier:CellIdentifier] autorelease];
    UIImageView * bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 84)];
    UIImage * bgImage;
    if ((indexPath.row % 2) == 0) {
      bgImage = [UIImage imageNamed:@"cell-even.png"];
    } else {
      bgImage = [UIImage imageNamed:@"cell-odd.png"];
    }
    [bgView setImage:bgImage];
    [bgImage release];
    [cell setBackgroundView:bgView];
    [bgView release];
    cell.title.text = [anArticle title];
    cell.author.text = [anArticle author];
    [cell setRating:[anArticle ratingAverage]];
    if (anArticle.imageSmall) {
      [NSThread detachNewThreadSelector:@selector(downloadCover:) toTarget:cell withObject:[anArticle imageSmall]];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  }
  return cell;
}

As of writing, customized cells do have some performance issues, scroll a list of customized cells is not smooth enough. Hope Apple would fix it in future.

Notice: cellForRowAtIndexPath method only executes when a cell is visible. And it can be executed multiple times when you scroll, so don’t do anything crazy in cellForRowAtIndexPath or it may crash the app easily.

Conclusion:

  • UITableView needs a datasource to guide it to draw cells.
  • Simple cells are filled by set text property.
  • Subclass UITableViewCell if you’re going to do complex drawing.
  • contentView and backgroundView are for complex drawing.
  • Don’t do expensive things in cellForRowAtIndexPath:.

Delegate

You can set an object as delegate like this:

[aTableView setDelegate:anObject];

So, now you know how to draw cells, but how to detect taps? This method in delegate object is for detecting taps:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

And there is another important method implemented by delegate:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

This method will tell UITableView how tall a cell will be. If you go the simple way, you don’t need implement heightForRowAtIndexPath in delegate, a default height will be set automatically.

If each cell holds different text and you want to have variable height, please refer to a post I wrote before:

How to make UITableViewCell have variable height

Now we’ve covered two basic important things in UITableView: datasource and delegate. With knowledge you’ve learned from this post, it’s sufficient for building read only iPhone data clients, and there are more topics like dynamic add/remove and editing, I’ll cover these topics later. If you find any bugs, typos or memory leaks in my code, welcome to tell me in comments, I’ll be very glad to know.

Fabrice

interesting ! I had myself spent some time understanding this. Should have read this sooner :) But it’s an excellent summary.

Kyle

Could you possibly give some further details for:
Aricle * anArticle = [[articles objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

I just couldn’t find the right syntax, and ended up doing it the hard way. There has to be an easier way.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int searchResultsEntryIndex = [indexPath indexAtPosition: [indexPath length] -1];
NSString *CellIdentifier = [[searchResultsEntries objectAtIndex: searchResultsEntryIndex] objectForKey: @”permalink”];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0,0,320,84) reuseIdentifier:CellIdentifier] autorelease];
[cell setText:[[searchResultsEntries objectAtIndex: searchResultsEntryIndex] objectForKey: @”title”]];
}
return cell;
}

Visitor

It appears that a possible performance issue is in the way you are reusing the cells. It would be best if the identifier of the cell was the same for all your cells in the table, this way, for any new article a UIImageView is not allocated along with other views you may be allocating in your custom cell. This will ensure only about 8-10 cells are created for the entire UITableView and you can reuse them every time, which will improve scrolling performance drastically.

David

I was struggling to work out UITableView for days until I found this article.
Keep up the good work!

Sowmya

This was a great post. Thanks for posting the detailed code, it helped a lot

Doug

Pure genius. Many thanks.

Some Objective-C Helpers for Data Wrangling « Variable Resistance | Just another WordPress weblog

[...] Learn Obj-C Shortlist Nick Myer’s Tutorials Simple linking to MP3 streaming content UITableView Overview { no comment } :| { Tags: [...]

Leave a Reply