您的位置:首页 > 移动开发 > IOS开发

iOS二级Table的简单实现

2015-08-10 11:37 387 查看
最近在项目中遇到一个小问题,就是用户点击table中的一行,将展开该Cell展示一个subTable。整个功能类似于点击QQ好友的分组,展开显示该分组下的好友列表。

该事件发生在用户点击该Cell的时候,因此需要在下面方法中编写代码:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (((UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]).isExpanded == NO)
{
((UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]).isExpanded = YES;

NSMutableArray * indexPaths = [[NSMutableArray alloc] init];
for (int i = 1; i <= _subTable.count; i++)
{
NSIndexPath * subIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + i)
inSection:indexPath.section];
[indexPaths addObject:subIndexPath];
}
[_subDataArr addObjectsFromArray:_subTable];

[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:
UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
else
{
((UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]).isExpanded = NO;

NSMutableArray * indexPaths = [[NSMutableArray alloc] init];
for (int i = 1; i <= _subDataArr.count; i++)
{
NSIndexPath * subIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + i) inSection:indexPath.section];
[indexPaths addObject:subIndexPath];
}
[_subDataArr removeAllObjects];

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:
UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
}


注释一下:
isExpanded是UITableViewCell的属性,用来判断当前的Cell是否已经展了。这个属性是自己添加的。
_subTable是一个全局的数组,里面存储了二级列表中的数据。
_subDataArr是table的dataSource源,而且还控制着numberOfRowInSection这个方法的返回值。因此每次添加数据到这里面时,该section中的row也同样会发生变化。

该方法来添加二级列表比较简单,核心思想就是通过对NSIndexPath的操作来动态改变table的Cell数。使用了tableView的两个方法,一个add方法和一个delete方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: