原文 : http://blog.csdn.net/youcanping2008/article/details/9202167
一、实现原理:就是在点击表格组头视图的时候,如果该表格视图的组展开了,就把改组的行设置为0,如果该组隐藏了,就显示该组的所有行。
效果如下:

二、实现步骤
1、定义一个数据模型用于封装数据
- #import <Foundation/Foundation.h>
-
- @interface MyData : NSObject
- {
- NSMutableArray *_array;
- BOOL _isShow;
- NSString *_name;
- }
- @property (nonatomic,retain) NSMutableArray *array;
- @property (nonatomic,copy) NSString * name;
- @property (nonatomic,assign) BOOL isShow;
- @end
2、添加数据源
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
-
- dataArray = [[NSMutableArray alloc] init];
-
- for (int i=‘A‘; i<=‘Z‘; i++) {
- MyData *myData = [[MyData alloc] init];
- myData.name = [NSString stringWithFormat:@"%c",i];
- for (int j=0; j<10; j++) {
- [myData.array addObject:[NSString stringWithFormat:@"%c-%d",i,j]];
- }
- [dataArray addObject:myData];
- }
- myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460-44) style:UITableViewStylePlain];
- myTableView.dataSource = self;
- myTableView.delegate = self;
- myTableView.rowHeight = 30;
- [self.view addSubview:myTableView];
- }
3.实现表格的代理方法
- - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
- {
- return [dataArray count];
- }
- - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- {
- MyData *data = [dataArray objectAtIndex:section];
- if ([data isShow]) {
- return [[data array] count];
- }else{
- return 0;
- }
- }
- - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *cellName = @"Cell";
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName ];
- if (!cell) {
- cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellName] autorelease];
- }
- MyData *data = [dataArray objectAtIndex:indexPath.section];
- NSString *str = [[data array] objectAtIndex:indexPath.row];
- cell.textLabel.text = str;
- return cell;
- }
4.自定义组的头标题视图,添加点击事件
- - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
- {
- MyData *data = [dataArray objectAtIndex:section];
-
- UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
- btn.frame = CGRectMake(0, 0, 320, 30);
- [btn setTitle:data.name forState:UIControlStateNormal];
- btn.tag = section;
- [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
- if (section%2) {
- btn.backgroundColor = [UIColor darkGrayColor];
- }else{
- btn.backgroundColor = [UIColor lightGrayColor];
- }
- return btn;
- }
- - (void) btnClick:(UIButton *)btn
- {
- MyData *data = [dataArray objectAtIndex:btn.tag];
-
- if ([data isShow]) {
- [data setIsShow:NO];
- }else{
- [data setIsShow:YES];
- }
-
- [myTableView reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationFade];
- }
【转】 iOS如何实现表格的折叠效果?
原文:http://www.cnblogs.com/A--G/p/4586060.html