iOS二级Table的简单实现

最近在项目中遇到一个小问题,就是用户点击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方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值