本文是一个关于简单的完成TableView段头点击能展开和收起功能的Demo
在ViewController.m
中如下:
#import "ViewController.h"
#define UIScreen_Width ([UIScreen mainScreen].bounds.size.width)
#define UIScreen_height ([UIScreen mainScreen].bounds.size.height)
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>{
UITableView* _tableView;
NSMutableArray *openArray;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
openArray = [[NSMutableArray alloc] init];
NSNumber* num = [NSNumber numberWithBool:YES];
//有几个section就要存几个openArray,在项目中就要注意这个openArray是根据后台数据获得的
[openArray addObject:num];
[openArray addObject:num];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, UIScreen_Width, UIScreen_height) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return openArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if ([[openArray objectAtIndex:section] boolValue] == NO) {
return 0;
}
return 10;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"ID"];
}
cell.textLabel.text = [NSString stringWithFormat:@"好友%ld",indexPath.row];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 35;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 0, UIScreen_Width, 35);
button.tag = section;
[button setBackgroundColor:[UIColor blueColor]];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
- (void)buttonClick:(UIButton*)button{
BOOL isOpen = [[openArray objectAtIndex:button.tag] boolValue];
if (isOpen == YES) {
NSNumber* num = [NSNumber numberWithBool:NO];
[openArray replaceObjectAtIndex:button.tag withObject:num];
} else {
NSNumber* num = [NSNumber numberWithBool:YES];
[openArray replaceObjectAtIndex:button.tag withObject:num];
}
[_tableView reloadSections:[NSIndexSet indexSetWithIndex:button.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
}
@end