我正在尝试实现具有以下结构的 uitableview:
- 部分组 0
- 第 0 节
- 单元格 0
- 单元格 1
- 单元格 2
- 第 1 节
- 单元格 0
- 单元格 1
- 单元格 2
- 第 0 节
- 第 1 组
- 第 0 节
- 单元格 0
- 单元格 1
- 单元格 2
- 第 1 部分
- 单元格 0
- 单元格 1
- 单元格 2
- 第 0 节
它应该像这个截图 (1-2-3-4): http://dl.dropbox.com/u/2213241/uitableview.png
所以总是有两个部分是可见的。
我该如何实现?或者有人已经实现了吗?
谢谢 :)
最佳答案
嵌套部分的诀窍是在 TableView 中有两种行。一个代表第二级部分,另一个代表 TableView 中的普通行。假设您有一个两级数组(比如部分)来表示 TableView 中的项目。
然后,我们拥有的部分总数就是顶级部分的数量。每个顶级部分中的行数将是子部分数 + 每个子部分中的行数。
- (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;
}
现在,我们需要考虑的是如何为 TableView 创建行。在 Storyboard中设置两个具有不同重用标识符的原型(prototype),一个用于节标题,另一个用于行项目,并根据数据源方法中的请求索引实例化正确的原型(prototype)。
- (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];
}
Here's a detailed post关于如何做到这一点。
关于ios - uitableview:嵌套的节标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7650243/