//要做分组最主要的就是控制tableView头视图的展开和收起,所以就必须要有布尔值来判断是展开还是收缩
BOOL close[16]; // NO表示展开 , YES表示收起
1.创建表视图;
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 375, 647) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
//组的头视图高度
_tableView,rowHeight = 44;
[self.view addSubview:_tableView];
//读取本地数据
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"font.plist" ofType:nil];
//初始化数组
_data = [[NSArray alloc] initWithContentsOfFile:filePath];
2.写代理方法
组的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return _data.count;
}
返回相应组里面有多少个单元格
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *array2D = _data[section];
BOOL isClose = close[section];
if (isClose) {
return 0;
}
return array2D.count;
}
//创建每一个单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *iden = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden] autorelease];
}
//取得组
NSInteger section = indexPath.section;
NSArray *array2D = _data[section];
//添加数据
cell.textLabel.text = array2D[indexPath.row];
return cell;
}
//设置组的头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//创建按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//设置tag
button.tag = section;
NSString *title = [NSString stringWithFormat:@"好友分组%ld",section];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//button点击事件
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
- (void)buttonAction:(UIButton *)button {
//取得点击的组
NSInteger section = button.tag;
取反
close[section] = !close[section];
[_tableView reloadData];
//刷新指定的组
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:section];
[_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
}
效果图如下: