@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.sectionStatus=[[NSMutableArray alloc]init];
NSString *path=[[NSBundle mainBundle]pathForResource:@"cities" ofType:@"plist"];
NSDictionary *dic=[NSDictionary dictionaryWithContentsOfFile:path];
self.provinces=[dic objectForKey:@"provinces"];
self.cities=[dic objectForKey:@"cities"];
//设置tableView的显示方式
// self.tableView.style=[UITableViewStyleGrouped ];
//初始化每组的状态
[self.provinces enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[self.sectionStatus addObject:@NO];
}];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.provinces.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSNumber *states=self.sectionStatus[section];
int count =0;
if ([states boolValue]) {
NSArray *city= [self.cities objectForKey:self.provinces[section]];
count=(int)city.count;
}
else
{
count=0;
}
//return city.count;
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID=@"cell";
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
NSArray *city= [self.cities objectForKey:self.provinces[indexPath.section]];
cell.textLabel.text=city[indexPath.row];
return cell;
}
#pragma mark 设置组名
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return self.provinces[section];
}
#pragma mark 设置每一组头部显示的视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIButton *btn=[[UIButton alloc]init];
//设置标题
[btn setTitle:self.provinces[section] forState:UIControlStateNormal];
//标题颜色
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//设置tag
btn.tag=section;
//点击事件
[btn addTarget:self action:@selector(sectionHeaderClicked:) forControlEvents:UIControlEventTouchUpInside];
return btn;
}
-(void)sectionHeaderClicked:(UIButton *)sender
{
//修改组显示的状态
NSNumber *state=self.sectionStatus[sender.tag];
if ([state boolValue]) { //原来上展开的 YES
[self.sectionStatus removeObjectAtIndex:sender.tag];
[self.sectionStatus insertObject:@NO atIndex:sender.tag];
}
else
{
[self.sectionStatus removeObjectAtIndex:sender.tag];
[self.sectionStatus insertObject:@YES atIndex:sender.tag];
}
//刷新表格数据
[self.tableView reloadData];
NSLog(@"section=%ld",sender.tag);
}
@end