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方法。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章