Creating A Simple iPad Application Table View

Creating A Simple iPad Application Table View

The best way to understand how to use a Table view in your iPad application is to create a new View-based Application project and then manually add a Table view to the view and wire it to a View Controller. That way, you understand the various building blocks of the Table view.

Without further ado, use the following Try It Out to create a new iPad project and see how to put a Table view together!

Try It Out Using a Table View

Codefile TableViewExample.zip available for download at Wrox.com

1. Create a new View-based Application project and name it TableViewExample.

2. Double-click the TableViewExampleViewController.xib file to edit it in Interface Builder.

3. Drag the Table View item from the Library and drop it onto the View window (see Figure 7-2).

 iPad application Drag the Table View item from the Library and drop it onto the View window

Figure 7-2

4. By default, the Table view fills up the entire View window. Resize the Table view to about a third of the width of the View window and set its Background color to a light yellow via the Attributes Inspector window (see Figure 7-3).

iPad application Resize the Table view

Figure 7-3

5. Right-click the Table view and connect the dataSource outlet to the File’s Owner item (see Figure 7-4). Do the same for the delegate outlet (see Figure 7-5).

connect the iPad Application dataSource outlet to the File’s Owner item

Figure 7-4

Figure 7-5

6. In the TableViewExampleViewController.h file, add the following bold statement:

#import <UIKit/UIKit.h>

            

@interface TableViewExampleViewController : UIViewController

    <UITableViewDataSource> {

}

            

@end

7. In the TableViewExampleViewController.m file, add the following statements that appear in bold:

#import "TableViewExampleViewController.h"

 

@implementation TableViewExampleViewController

 

NSMutableArray *listOfMovies;

 

//—insert individual row into the table view—

– (UITableViewCell *)tableView:(UITableView *)tableView

         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 

    static NSString *CellIdentifier = @"Cell";

    

    //—try to get a reusable cell—

    UITableViewCell *cell = [tableView

        dequeueReusableCellWithIdentifier:CellIdentifier];

 

    //—create new cell if no reusable cell is available—

    if (cell == nil) {

        cell = [[[UITableViewCell alloc]

                   initWithStyle:UITableViewCellStyleDefault

                 reuseIdentifier:CellIdentifier] autorelease];

    }

    

    //—set the text to display for the cell—

    NSString *cellValue = [listOfMovies objectAtIndex:indexPath.row];

    cell.textLabel.text = cellValue;

    

    return cell;

//—set the number of rows in the table view—

– (NSInteger)tableView:(UITableView *)tableView

numberOfRowsInSection:(NSInteger)section {

 

    return [listOfMovies count];

}

 

– (void)viewDidLoad {

 

    //—initialize the array—

    listOfMovies = [[NSMutableArray alloc] init];

    

    //—add items—

    [listOfMovies addObject:@"Training Day"];

    [listOfMovies addObject:@"Remember the Titans"];

    [listOfMovies addObject:@"John Q."];

    [listOfMovies addObject:@"The Bone Collector"];

    [listOfMovies addObject:@"Ricochet"];

    [listOfMovies addObject:@"The Siege"];

    [listOfMovies addObject:@"Malcolm X"];

    [listOfMovies addObject:@"Antwone Fisher"];

    [listOfMovies addObject:@"Courage Under Fire"];

    [listOfMovies addObject:@"He Got Game"];

    [listOfMovies addObject:@"The Pelican Brief"];

    [listOfMovies addObject:@"Glory"];

    [listOfMovies addObject:@"The Preacher’s Wife"];

    

    [super viewDidLoad];

}

 

– (void)dealloc {

    [listOfMovies release];

    [super dealloc];

}

8. Press Command-R to test the application on the iPhone Simulator. Figure 7-6 shows the Table view displaying the list of movies.

iPhone simulator Table view displaying ipad application list

Figure 7-6

How It Works

You actually start the application in step 7 by creating an NSMutableArray object called listOfMovies containing a list of movies names. The items stored in this array will be displayed by the Table view.

– (void)viewDidLoad {

 

    //—initialize the array—

    listOfMovies = [[NSMutableArray alloc] init];

    

    //—add items—

    [listOfMovies addObject:@"Training Day"];

    [listOfMovies addObject:@"Remember the Titans"];

    [listOfMovies addObject:@"John Q."];

    [listOfMovies addObject:@"The Bone Collector"];

    [listOfMovies addObject:@"Ricochet"];

    [listOfMovies addObject:@"The Siege"];

    [listOfMovies addObject:@"Malcolm X"];

    [listOfMovies addObject:@"Antwone Fisher"];

    [listOfMovies addObject:@"Courage Under Fire"];

    [listOfMovies addObject:@"He Got Game"];

    [listOfMovies addObject:@"The Pelican Brief"];

    [listOfMovies addObject:@"Glory"];

    [listOfMovies addObject:@"The Preacher’s Wife"];

    

    [super viewDidLoad];

}

To populate the Table view with items, you need to handle several events contained in the UITableViewDataSource protocol. Hence, you need to ensure that your view controller conforms to this protocol:

@interface TableViewExampleViewController : UIViewController

   <UITableViewDataSource> {

}

NOTE: Strictly speaking, if you have connected the dataSource outlet to the File’s Owner item, you don’t need to add the preceding statement. However, doing both doesn’t hurt anything. There is one advantage to adding the <UITableViewDataSource> protocol, though — the compiler will warn you if you forget to implement any mandatory methods in your code, helping to prevent errors.

The UITableViewDataSource protocol contains several events that you can implement to supply data to the Table view. Two events handled in this example are:

  • tableView:numberOfRowsInSection:

  • tableView:cellForRowAtIndexPath:

The tableView:numberOfRowsInSection: event indicates how many rows you want the Table view to display. In this case, you set it to the number of items in the listOfMovies array:

//—insert individual row into the table view—

– (NSInteger)tableView:(UITableView *)tableView

numberOfRowsInSection:(NSInteger)section {

            

   return [listOfMovies count];

            

}

The tableView:cellForRowAtIndexPath: event inserts a cell in a particular location of the Table view. This event is fired once for each row of the Table view.

Here, you retrieve the individual item from the array and insert it into the Table view:

– (UITableViewCell *)tableView:(UITableView *)tableView

         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 

    static NSString *CellIdentifier = @"Cell";

 

    //—try to get a reusable cell—

    UITableViewCell *cell = [tableView

        dequeueReusableCellWithIdentifier:CellIdentifier];

 

    //—create new cell if no reusable cell is available—

    if (cell == nil) {

        cell = [[[UITableViewCell alloc]

                   initWithStyle:UITableViewCellStyleDefault

                 reuseIdentifier:CellIdentifier] autorelease];

    }

 

    //—set the text to display for the cell—

    NSString *cellValue = [listOfMovies objectAtIndex:indexPath.row];

    cell.textLabel.text = cellValue;

    

    return cell;

}

Specifically, you use the dequeueReusableCellWithIdentifier: method of the UITableView class to obtain an instance of the UITableViewCell class. The dequeueReusableCellWithIdentifier: method returns a reusable Table view cell object. This is important because if you have a large table (say, with 10,000 rows) and you create a single UITableViewCell object for each row, you would generate a great performance and memory hit. Also, because a Table view displays only a fixed number of rows at any one time, reusing the cells that have been scrolled out of view would make more sense. This is exactly what the dequeueReusableCellWithIdentifier: method does. So, for example, if 10 rows are visible in the Table view, only 10 UITableViewCell objects are ever created — they always get reused when the user scrolls through the Table view.

NOTE: The tableView:cellForRowAtIndexPath: event is not fired continuously from start to finish. For example, if the Table view has 100 rows to be displayed, the event is fired continuously for the first, say, 10 rows that are visible. When the user scrolls down the Table view, the tableView:cellForRowAtIndexPath: event is fired for the next couple of visible rows.

This article is excerpted from chapter 7 "Using the Table View" of the book Beginning iPad Application Development by Wei-Meng Lee (ISBN: 978-0-470-64165-1, Wrox, 2010, Copyright Wiley Publishing Inc.)

Tags:

Comments

One response to “Creating A Simple iPad Application Table View”

  1. Anonymous says:

     Hi there! 
    Great example. Just one thing I wonder about.
    Is there any way to create two separate tableview on one iPad view? How can I add content to these separately. 
     
    Sincerely,
     
    Oystein Saebo

Leave a Reply

Your email address will not be published. Required fields are marked *