-
iPhone tableView
Posted on March 2nd, 2009 2 commentsThe Table View is widely used in iPhone apps, and ther are many examples of using it on navigation pages in the iPhone SDK example programs. These examples generally show how to add a tableView that fills the screen, or sometimes with a Navigation Bar element at the top.
Sometimes, we want to use a table view as a smaller element within another view. The iPhone Clock app uses this approache in stopwatch mode to show the lap times.
In this case, the view that contains the TableView will typically be a subclass of UIViewController. We need only add the protocols UITableViewDelegate and UITableViewDataSource to our view. This is done in the header file:
#import <UIKit/UIKit.h> @interface MyViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{ } @end
For a simple view, we will need to add the numberOfRowsInSection and cellForRowAtIndex methods. This example shows a table of 5 rows, with cells labeled Item #0 to Item #4.
#import "MyViewController.h" @implementation MyViewController - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 5; // we want 5 rows in our table. } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ NSString *Identifier = [ [NSString alloc] initWithFormat:@"Item #%d", [indexPath indexAtPosition:1] ]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier]; if (cell == nil){ cell = [ [ [UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: Identifier] autorelease]; } cell.text = Identifier; return cell; } @end
In interface builder, connect the datasource and delegate outlets from your table view directly to file’s owner. There is no need to add a tableViewController to the nib.

