这篇文章主要整理一下项目中用到的类似qq通讯录的收缩功能。
我实现的思路是在tableview的header放置button,然后根据button是否选中来判断是否需要显示那一个section。
首先定义了两个属性
1
2
|
@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSArray *buttonsArr;
|
button数组的定义
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
-(NSArray *)buttonsArr{
if
(_buttonsArr==nil) {
NSMutableArray *tmp=[NSMutableArray array];
for
(
int
i=
0
; i<
6
; i++) {
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.tag=
333
+i;
button.backgroundColor=[UIColor redColor];
[button setTitle:[NSString stringWithFormat:@
"%d"
,i] forState:UIControlStateNormal];
button.selected=NO;
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[tmp addObject:button];
}
_buttonsArr=[NSArray arrayWithArray:tmp];
}
return
_buttonsArr;
}
|
按钮的点击方法,根据按钮的选中状态刷新tableview
1
2
3
4
5
6
|
-(
void
)buttonAction:(UIButton *)button{
button.selected=!button.isSelected;
[self.tableview reloadSections:[NSIndexSet indexSetWithIndex:button.tag-
333
] withRowAnimation:UITableViewRowAnimationFade];
}
|
tableview的一系列代理方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return
self.buttonsArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
UIButton *button=self.buttonsArr[section];
if
(button.selected==YES) {
return
1
;
}
else
{
return
0
;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static
NSString *str=@
"cellid"
;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:str];
if
(cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
cell.textLabel.text=[NSString stringWithFormat:@
"第%li节"
,indexPath.section];
}
return
cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIButton *button=self.buttonsArr[section];
return
button;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return
150
;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return
50
;
}
|