类似qq分组栏-动态分组

本文介绍如何使用UITableView实现分组数据的加载与显示,并通过按钮控制各组数据的显示与隐藏状态。代码中详细展示了如何初始化UITableView并设置数据源及代理方法,包括创建UITableViewCell、配置HeaderView等。
.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;
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值