LeBrequin
LeBrequin

Reputation: 137

Put a cell in specific section of a Table View

I have a table view controller with three sections and I don't know how I can choose in which sections I want to put cells after a condition for exemple. And also to define the number of cell per section dynamically.

In my code, I have 3 sections, I know that I will have only 1 cell for the section "Present show" but for the other section it depends of the number of show

My code :

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *sectionName;
    switch (section)
    {
        case 0:
            sectionName = @"Past show";
            break;
        case 1:
            sectionName = @"Currentshow";
            break;
        default:
            sectionName = @"Futur Show";
            break;
    }
    return sectionName;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.scheduleList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    TVShow *tvc = self.scheduleList[indexPath.row];
    cell.textLabel.text = tvc.title;
    cell.textLabel.textColor = [UIColor blackColor];
    if ([self isTimeForAshow: tvc]) {
        cell.textLabel.textColor = [UIColor redColor];
       // NSLog(@"%@ -time for show %@, show duration %@", tvc.title, tvc.startTime, tvc.duration);
    }
    cell.detailTextLabel.text = tvc.startTime;

    return cell;
}

Thanks for your help

Upvotes: 1

Views: 697

Answers (1)

Hélène Martin
Hélène Martin

Reputation: 1441

You could maintain three lists of schedules (e.g. pastScheduleList, currentScheduleList, futureScheduleList). You can then use a similar test structure as the one you use in tableView:titleForHeaderInSection: in tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath:. For example, for tableView:numberOfRowsInSection::

NSInteger sectionCount;
switch (section)
{
    case 0:
        sectionCount = [self.pastScheduleList count];
        break;
    case 1:
        sectionCount = [self.currentScheduleList count];
        break;
    default:
        sectionCount = [self.futureScheduleList count];
        break;
}
return sectionCount;

For tableView:cellForRowAtIndexPath:, you will need to switch on indexPath.section.

Upvotes: 2

Related Questions