The trick to have nested partitions must have two kinds of rows in the table view. One for representing the second level of partitions, and another for representing ordinary rows in a table view. Say you have a two-level array (e.g. partitions) to represent elements in a table view.
Then the total number of partitions that we have is simply the number of top-level partitions. The number of rows in each top-level section will be the number of sub-sections + the number of rows in each subsection.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return self.sections.count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSArray *sectionItems = self.sections[(NSUInteger) section]; NSUInteger numberOfRows = sectionItems.count;
Now we only need to think about how to create rows to represent the table. Set up two prototypes in the storyboard with different reuse identifiers, one for the section heading and the other for the line item, and just create the correct one based on the requested index in the data source method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSMutableArray *sectionItems = self.sections[(NSUInteger) indexPath.section]; NSMutableArray *sectionHeaders = self.sectionHeaders[(NSUInteger) indexPath.section]; NSIndexPath *itemAndSubsectionIndex = [self computeItemAndSubsectionIndexForIndexPath:indexPath]; NSUInteger subsectionIndex = (NSUInteger) itemAndSubsectionIndex.section; NSInteger itemIndex = itemAndSubsectionIndex.row; if (itemIndex < 0) { // Section header UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SECTION_HEADER_CELL" forIndexPath:indexPath]; cell.textLabel.text = sectionHeaders[subsectionIndex]; return cell; } else { // Row Item UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ROW_CONTENT_CELL" forIndexPath:indexPath]; cell.textLabel.text = sectionItems[subsectionIndex][itemIndex]; return cell; } } - (NSIndexPath *)computeItemAndSubsectionIndexForIndexPath:(NSIndexPath *)indexPath { NSMutableArray *sectionItems = self.sections[(NSUInteger) indexPath.section]; NSInteger itemIndex = indexPath.row; NSUInteger subsectionIndex = 0; for (NSUInteger i = 0; i < sectionItems.count; ++i) { // First row for each section item is header --itemIndex; // Check if the item index is within this subsection items NSArray *subsectionItems = sectionItems[i]; if (itemIndex < (NSInteger) subsectionItems.count) { subsectionIndex = i; break; } else { itemIndex -= subsectionItems.count; } } return [NSIndexPath indexPathForRow:itemIndex inSection:subsectionIndex]; }
Here is a detailed post on how to do this.
source share