Question

I would a grouped tableview such that:

  • when the only row of the first section is associated to a state, say A, I can see only this first section with, possibly, some text under it (in a footer for example);

  • when this state changes, I would see other sections under the first;

How could I achieve this? Some code/link to obtain something similar?

Thanks,

Fran

Was it helpful?

Solution

No problem, just add some if else logic in all your tableView Datasource and delegate methods.

For example like this:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (!canUseInAppPurchase || isLoading) {
        return 1;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!canUseInAppPurchase || isLoading) {
        return 1;
    }
    if (section == 0) {
        // this will be the restore purchases cell
        return 1;
    }
    return [self.products count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    cell = ...
    NSString *cellText = nil;
    if (!canUseInAppPurchase) {
        cellText = @"Please activate inapp purchase";
    }
    else if (isLoading) {
        cellText = @"Loading...";
    }
    else {
        if (section == 0) {
            cellText = @"Restore purchases";
        }
        else {
            cellText = productName
        }
    }
    cell.textLabel.text = cellText;
    return cell;
}

and if you want to add or remove the second section you could use a simply [tableView reloadData]; or this smoother variant:

[self.tableView beginUpdates];
if (myStateBool) {
    // activated .. show section 1 and 2
    [self.tableView insertSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 2)] withRowAnimation:UITableViewRowAnimationTop];
}
else {
    // deactivated .. hide section 1 and 2
    [self.tableView deleteSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 2)] withRowAnimation:UITableViewRowAnimationBottom];
}
[self.tableView endUpdates];

be careful, you have to change the data in your datasource first. And this code will add 2 sections. But you can adopt it to your needs easily.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top