Derek Martin
Derek Martin

Reputation: 61

How To Implement UITableView Sections

Here's my situation. I'm building an RSS app. I need my stories to display in a section based on the time of day. There are 3 categories (AM Stories, PM Stories, and Editorials). I get these categories directly from the RSS feed.

How is the best way to go about this? There will always be Editorials and there will always be AM Stories -- only PM Stories is variable. Currently, I've made three arrays to hold the RSS items for each respective story. I'm hung up on returning the correct number of sections to the UITableView data source and how to know what section # corresponds to the respective section (i.e. Does section 0 equal Editorials or does it equal AM Stories?)

I really appreciate any help you can give me.

Upvotes: 0

Views: 1045

Answers (1)

jonkroll
jonkroll

Reputation: 15722

Your tableViews sections will be numbered sequentially, starting with 0. If you have no PM Stories, then AM stories will be section 0 and editorials will be section 1. If you DO have PM stoires, then AM stories will be section 0, PM stories will be section 1, and editorials will be section 2.

You can return the correct number of section from numberOfSectionsInTableView: based on whether your PM Stories array is empty or not:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([pmStoresArray count] > 0) {
        return 3;
    } else {
        return 2;
    }
}

Then in cellForRowAtIndexPath: you can use the same logic to determine which section's category the cell belongs to:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if (indexPath.section == 0) {
        // am stories cell

    } else if (indexPath.section == 1 && [pmStoriesArray count] > 0) {
        // pm stories cell

    } else {
        // editorials cell

    }

    return cell;
}

Upvotes: 1

Related Questions