简体   繁体   中英

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 (ie Does section 0 equal Editorials or does it equal AM Stories?)

I really appreciate any help you can give me.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM