类似qq分组栏-动态分组

来源:互联网 发布:p5.js正方形 编辑:程序博客网 时间:2024/04/30 06:33
.h 
  文件
(void)viewDidLoad {
   [super viewDidLoad];
   _tableView = [[UITableView alloc] initWithFrame:[UIScreenmainScreen].bounds style:UITableViewStylePlain];
   _tableView.delegate = self;
   _tableView.dataSource = self;

   [self.view addSubview:_tableView];
   _array = [[NSMutableArray alloc] initWithObjects:[[NSArray alloc]initWithObjects:@"AA",@"BB",@"CC",@"DD",nil],
                                        [[NSArray alloc]initWithObjects:@"EE",@"FF",@"GG",@"XX",@"ZZ",nil],   
                                        [[NSArray alloc]initWithObjects:@"JJ",@"VV",@"EE",@"NN",nil],
                                        nil];
   flag = (BOOL*)malloc([_arraycount]*sizeof(BOOL*));
   memset(flag, NO, sizeof(flag));

}

.m文件的内容

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
   return [_array count];
}



-(NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section {
   return [self numberOfRowsInSection:section];
}

- (UITableViewCell*)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier =@"CellIdentifier";
   UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {
       cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier] autorelease];
       cell.selectionStyle =UITableViewCellSelectionStyleNone;
   }
   NSString* str = [[_array objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
   cell.textLabel.text = str;
   return cell;
}



- (UIView*)tableView:(UITableView *)tableViewviewForHeaderInSection:(NSInteger)section
{
   UIButton *abtn = [UIButtonbuttonWithType:UIButtonTypeInfoDark];
   abtn.frame = CGRectMake(0, 0, 200, 100);
   abtn.titleLabel.text = @"HEADER";
   abtn.tag = section;
   [abtn addTarget:self action:@selector(headerClicked:)forControlEvents:UIControlEventTouchUpInside];
   return abtn;
}

////////////////////////////////////////////////////////////////////////////////////////
//
-(void)headerClicked:(id)sender
{
   int sectionIndex = ((UIButton*)sender).tag;
   flag[sectionIndex] = !flag[sectionIndex];
   [_tableView reloadData];
}

-(int)numberOfRowsInSection:(NSInteger)section
{
   if (flag[section]) {
       return[(NSArray*)[_array objectAtIndex:section] count];
   }
   else {
       return0;
   }
}