iOS中的二级菜单及Cell的展开收起示例

时间:2022-11-03 14:31:51

最近又做了一个项目,涉及到二级菜单及cell的展开收起,这是我所做过的第三个项目中做这个功能了,我当然不能把公司的项目界面show出来,所以我重新创建一个工程,数据都写的是固定的数据。作为总结,记录实现过程,及要注意的一些点:如进来默认选中第一行,数据优化等。

先看看我们实现的效果:

iOS中的二级菜单及Cell的展开收起示例

基本ui布局思路:

1.将view分为左右两部分,左,右分别是一个tableview

2.点击左边的cell时候,刷新右边的数据

需要注意及处理的点有:

1.默认进来界面显示左边选中第一行,及对应右边的数据

2.每次点击左边的cell,右边都需要刷新数据,如果每次点击左边都要请求一次数据,那么会很消耗用户的流量

3.cell的展开收起我们通过cell 的高度变化实现

在这里主要罗列需要注意的那三点,功能的全部实现我已经提交到github,需要的伙伴,可以去下载https://github.com/mumuna/aboutcell

首先说明,一般类似这样的布局,后台提供接口,左边的tableview的数据源会是一个接口,左边的tableview的每个cell对应的右边的数据也是一个接口,但是不同的cell需要传入id请求获取对应的数据,这样每点击一个左边的cell就需要请求一次右边的数据。

1.初次进入界面默认显示左边第一行及对应的右边的数据,及数据优化

(1)首先获取到左边的tableview所需的数据及第一行对应的右边的数据
(2)其它cell对应的右边的数据我们在tableview didselectrowatindexpath 方法中请求获得
(3)默认选中第一行

?
1
2
3
//默认选中第一行
 nsindexpath *ip=[nsindexpath indexpathforrow:0 insection:0];
 [lefttable selectrowatindexpath:ip animated:yes scrollposition:uitableviewscrollpositionbottom];

(4)在tableview didselectrowatindexpath 方法中,根据点击的左边的cell,请求右边的数据。我们不能每次点击都请求一次,这样很耗费用户的流量。

我们需要把右边的数据放在可变数组里arr,全部初始化arr = [nsmutable array];,每次点击,先判断arr.count ==0 ,如果!=0 再去请求数据,然后reload data。

2.cell的弹开和收起

在效果图中可以看到点击tableview的区的headerview,对应区的row会弹开收起。

(1)我们在获取数据的时候,创建一个数组,给每个区的headerview一个标志“0”,即默认为收起

?
1
2
3
4
5
//specificaarr是效果图中左边的cell英国,对应的右边的数据源
//flagarr是左边对每个区的标识
for (int i = 0; i<specificarr.count; i++) {
    [flagarr addobject:@"0"];
          }

(2)给headerview添加一个手势,且给headerview一个tag值方便在手势响应事件中知道我们具体点击的是哪个区

?
1
2
3
view.tag = 100+section;
uitapgesturerecognizer *tap = [[uitapgesturerecognizer alloc]initwithtarget:self action:@selector(sectionclick:)];
[view addgesturerecognizer:tap];

(3)在手势响应事件中根据headerview的标识选择展开还是收起row,且改变标识

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-(void)sectionclick:(uitapgesturerecognizer *)tap{
//根据tag值获取点击的区
  int index = tap.view.tag%100;
//创建可变数据,存储所点击的区的所有行的indexpath,tableview刷新区对应的行,重新设置行高
  nsmutablearray *indexarray = [[nsmutablearray alloc]init];
  nsarray *arr = specificarr[index];
  for (int i = 0; i<arr.count; i++) {
    nsindexpath *path = [nsindexpath indexpathforrow:i insection:index];
    [indexarray addobject:path];
  }
  //展开
  if ([flagarr[index] isequaltostring:@"0"]) {
    [flagarr replaceobjectatindex:index withobject:@"1"];
    [specifictable reloadrowsatindexpaths:indexarray withrowanimation:uitableviewrowanimationbottom];
  }else{
    [flagarr replaceobjectatindex:index withobject:@"0"];
    [specifictable reloadrowsatindexpaths:indexarray withrowanimation:uitableviewrowanimationbottom];
  }
}

(4)在tableview heightforrowatindexpath方法中设置tableview的高度

?
1
2
3
4
5
if ([flagarr[indexpath.section] isequaltostring:@"0"]) {
     return 0;
   }else{
     return 96;
   }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.jianshu.com/p/620066a416e7?utm_source=tuicool&utm_medium=referral