Хитрость в том, чтобы иметь вложенные разделы, состоит в том, чтобы иметь два вида строк в табличном представлении.Один для представления второго уровня разделов, а другой для представления обычных строк в табличном представлении.Допустим, у вас есть двухуровневый массив (скажем, разделы) для представления элементов в табличном представлении.
Тогда общее количество секций, которое у нас есть, это просто количество секций верхнего уровня.Количество строк в каждом разделе верхнего уровня будет равно числу подразделов + количество строк в каждом подразделе.
- (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; // For second level section headers
for (NSArray *rowItems in sectionItems) {
numberOfRows += rowItems.count; // For actual table rows
}
return numberOfRows;
}
Теперь все, что нам нужно подумать, - это как создать строки для таблицы.Посмотреть.Установите два прототипа в раскадровке с разными идентификаторами повторного использования, один для заголовка раздела и другой для элемента строки, и просто создайте правильный экземпляр на основе запрашиваемого индекса в методе источника данных.
- (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's items
NSArray *subsectionItems = sectionItems[i];
if (itemIndex < (NSInteger) subsectionItems.count) {
subsectionIndex = i;
break;
} else {
itemIndex -= subsectionItems.count;
}
}
return [NSIndexPath indexPathForRow:itemIndex inSection:subsectionIndex];
}
Вот подробный пост о том, как это сделать.