美文网首页iOS开发攻城狮的集散地
iOS 列表(UITableView)展开

iOS 列表(UITableView)展开

作者: 罗显友 | 来源:发表于2017-12-07 15:07 被阅读205次
图片: 展开列表图片

需要做一个列表展开功能,先分析一下思路。
1.列表展开需要设置tableVbiew的类型是 “组” 类型
2.数据源的数据结构应该是需要满足分组需求的。比如有多组数据
3.有一个数组,里面的元素需要和数据源数组中的元素一样多,用来控制刷新哪一组数据源
4.原理就是:判断当前点击的是哪一组section,然后刷新这一组的数据,而且返回的cell高度为0或者cell的总体高度,这样就可以满足展开和合并这个功能。
这里我觉得可以让后台返回一个字段,在每一组数据中都存在,然后在本地解析存到一个数组中,作为判断section当前展开或者合并的状态。
还有一种就是获取到数据源数组中有多少组元素,然后依次向一个数组里面添加对应个数的元素进去,然后用来判断section的合并和展开。

1.构建一个数据源数组

#pragma  数据源数组   构建一个数据源数组sectionArr
-(void)makeSuoreArray
{
    self.sectionArr = [NSMutableArray array];
    self.indexRowArr = [NSMutableArray array];
    for (int i = 0; i < 6; i++) {
        //添加每一组cell
        NSMutableArray *cellArr = [NSMutableArray array];
        for(int j = 0; j < arc4random()%10 + 1; j ++){
            NSString * cellStr = [NSString stringWithFormat:@"第%d行cell",j];
            [cellArr addObject:cellStr];
        }
        [self.sectionArr addObject:cellArr];
        [self.indexRowArr addObject:@"0"];
    }
    NSLog(@"%@",self.sectionArr);
}

2.给section添加点按手势

 //添加手势  (在section中添加了一个label,然后给label添加的手势)
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openlist:)];
    [sectionHeardLabel addGestureRecognizer:tap];

3.实现点按手势的监听方法,用来控制列表的展开和合并

这个方法里面主要就是刷新列表,重点是制定刷新哪一组的哪些cell,所以第一步需要获取到对应的scetion和对应的cell,然后再判断当前section的状态来控制刷新列表,然后返回不同的cell高度。
#pragma 手势
-(void)openlist:(UITapGestureRecognizer *)tap
{
    NSLog(@"我点击了%ld行",tap.view.tag);
    int index = tap.view.tag % 10;
    NSMutableArray *indexArray = [NSMutableArray array];
    NSArray *arr = self.sectionArr[index];
    for (int i = 0; i < arr.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:index];
        [indexArray addObject:indexPath];
    }
    if ([self.indexRowArr[index] isEqualToString:@"0"]) {
        self.indexRowArr[index] = @"1";
        [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationBottom];
    }else
    {
        self.indexRowArr[index] = @"0";
        [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationTop];
    }
}

4.cell高度的返回

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.indexRowArr[indexPath.section] isEqualToString:@"0"])
    {
        return 0;
    }else{
        return 64;
    }
}

下载文件点击这里:github

相关文章

网友评论

本文标题:iOS 列表(UITableView)展开

本文链接:https://www.haomeiwen.com/subject/huelixtx.html