Lecture #9: Table Views

Please note, this blog entry is from a previous course. You might want to check out the current one.

Lecture nine is named “9. Table Views (October 25, 2011)” and can be found at iTunes. Its slides are available at Stanford.

The theoretical part starts with table views which allow to display static or dynamic lists of data in different styles. A table consists of a header, a footer and table cells possible divided in sections (also with a header and a footer). A cell can be of type subtitle, basic, right and left detail, as well as completely customized.

Most of the setup can be setup directly in storyboard but it can also be accessed via code, especially when creating dynamic tables, e.g. to create cells

- (UITableViewCell *)tableView:(UITableView *)sender
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
    UITableViewCell *cell;
    cell = [self.tableView dequeueReusableCellWithIdentifier:@“My Table View Cell”];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:@“My Table View Cell”];
    cell.textLabel.text = [self getMyDataForRow:indexPath.row inSection:indexPath.section];
    return cell;

or to get the number of rows

- (NSInteger)numberOfSectionsInTableView:(UITableView *)sender;
- (NSInteger)tableView:(UITableView *)sender numberOfRowsInSection:(NSInteger)section;

or to know a row has been selected

- (void)tableView:(UITableView *)sender didSelectRowAtIndexPath:(NSIndexPath *)path 
    // go do something based on information
    // about my data structure corresponding to indexPath.row in indexPath.section

When used as segue it is also possible to know which row has been accessed

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    // prepare segue.destinationController to display based on information
    // about my data structure corresponding to indexPath.row in indexPath.section 

If the data of a table changes the data can be reloaded completely

- (void)reloadData;

or only a part of it

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths

The demo of this lecture shows the just learned by adding a favorites feature to the calculator. Code for this demo is available at Stanford in two version: the actual code shown during the demo and code with additional features to support the iPhone and removing items from the favorites list. The adjusted code from the assignments is available at github.


Leave a Reply

Your email address will not be published.