David Janes' Code Weblog

March 23, 2009

iPhone How To: create a Simple Table

code fragments, iphone · David Janes · 8:08 am ·

If you have not created a XIB, do the following:

  • select Resources in the Interface Building
  • press ⌘N
  • select User Interfaces in iPhone OS
  • select View XIB … and create in the normal way

To create the Simple Table in the Interface Builder

  • open the XIB in Resources
  • drag the Table View from the Library to the View … it should resize to the full extent of the View
  • select the Table View object and press ⌘2
  • from the Outlets section, drag
    • dataSource to File’s Owner
    • delegate to File’s Owner
  • save

Make your Controller.h a data source and delegate for the table:

@interface ThemesController : UIViewController
<UITableViewDelegate, UITableViewDataSource>
{
}

Add the following basic code to the Controller.m file:

#pragma mark -
#pragma mark Table View Data Source Methods

- (NSInteger) tableView:(UITableView*) tableView numberOfRowsInSection:(NSInteger) section
{
  return  ... the number of rows ...;
}

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

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

  NSUInteger row = [indexPath row];
  cell.text = ... an NSString containing what to display for row row ...;
  // cell.image = [UIImage imageNamed:@"star.png"];

  return  cell;
}

#pragma mark -
#pragma mark Table Delegate Methods

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

Compile and run.

0 comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress