Pages

Monday, August 2, 2010

iPhone Tableview Tutorial Part 1

With the navigation-based application template it is very easy to implement a tableview in iOS, most of the work of already done for you and you only need to add in your data and change some methods.

For this tutorial we will create a simple table of gadgets.

1. Start a new project in Xocode and select the navigation-based application template. Leave other options unchecked. click Choose and enter BasicTableView for the name.

2. You will notice 2 pairs of classes created for you. RootViewController and BasicTableViewAppDelegate. Open RootViewController.h You will notice it is a derived from UITableViewController. First, we are going to declare a simple array to hold our the names of our gadgets:
@interface RootViewController : UITableViewController {
 NSArray *gadgets;
}

@end

3. Next we are going to initialise our array with data when our the view loads. Uncomment the viewDidLoad method and add the following line:
gadgets = [[NSArray alloc] initWithObjects:@"Google Nexus One",@"Google Nexus S",
                  @"iPhone",@"iPhone 3G",@"iPhone 3GS",@"iPhone 4",
                  @"Macbook",@"Macbook Pro",@"Macbook Air",nil]; 

4. Now we get to the TableView methods used to display our data in the TableView. Right now there are only 2 methods we need to be concerned with. Scroll down and locate tableView:numberOfRowsInSection method. This method determines how many rows in each section of the tableview(We only have 1 section at the moment). The size of the gadgets array also happens to be the number of rows we want to have so:
- (NSInteger)tableView:(UITableView *)tableView 
                       numberOfRowsInSection:(NSInteger)section {
    return gadgets.count;
}

5. Next we need to modify tableView:cellForRowAtIndexPath for each row cell to display the data from the array. We only need to add 1 line at this point before the Return cell statement:
//Set content of cell
    cell.textLabel.text=[gadgets objectAtIndex:indexPath.row];

    return cell;

cell is the object representing the row cell that is being created and displayed in the table view. It reads the array at an index which corresponds to the index of the current row in the table view.

That's it. Run the application and you should see the list of items you defined in gadgets displayed. If you increase the number of items you should be able to scroll through them. Change the return result in numberOfSectionsInTableView to see the effect. In subsequent tutorials we will look at how you can further customise the tableview and display additional data.

No comments:

Post a Comment