iPhone UITableView嵌套部分
对于acani iPhone应用程序,我想在UITableView
显示组(基于兴趣)。 我想用分类学方式组织这些小组,例如:
- 体育
- 蝙蝠和球
- 棒球
- 垒球
- 蟋蟀
- 曲棍球
- 曲棍球
- 冰球
- 滚轴曲棍球
- 蝙蝠和球
- 工程
- 电气工程
- 生化工程
我该如何在UITableView
上安排这个?
我认为应该有一个根UITableView
将有运动和工程部分,细胞蝙蝠球和曲棍球将在体育部分下,细胞电气工程和生化工程将在工程部分。
然后蝙蝠和球应该有自己的UITableView
,它应该有细胞棒球,垒球和板球。
这听起来像是安排用户界面的好方法吗?
你有这样的用户界面的Xcode示例代码的示例代码或链接吗? 必须有一个像这样的Xcode示例项目。 也许是元素周期表项目或Core Data Books?
谢谢!
马特
你说对了。 UITableView
实际上并不是设计为显示层次结构和行的两个以上级别。 如果要显示两个以上的级别,在大多数(所有?)iOS应用程序中使用“向下钻取”方法,其中点击一行会在导航堆栈上显示另一个UITableView
。 (正如你所说。)
有许多Apple示例代码项目使用此设计模式。
编辑:刚刚检查过, DrillDownSave就是一个很好的例子,就像SimpleDrillDown一样 。
嵌套部分的技巧是在表视图中有两种行。 一个表示第二级部分,另一个表示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; }
现在,我们需要考虑的是如何为表视图创建行。 在故事板中设置两个具有不同重用标识符的原型,一个用于节头,另一个用于行项,并根据数据源方法中的询问索引实例化正确的原型。
- (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]; }
这是一篇关于如何做到这一点的详细文章 。