.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)numberOfSectionsInTableV iew:(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 = [tableViewdequeueReusableCellWithI dentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefa ultreuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle =UITableViewCellSelection StyleNone;
}
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:UIControlEventTouchUpIns ide];
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;
}
}
(void)viewDidLoad {
}
.m文件的内容
-(NSInteger)numberOfSectionsInTableV
}
-(NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section {
}
- (UITableViewCell*)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (UIView*)tableView:(UITableView *)tableViewviewForHeaderInSection:(NSInteger)section
{
}
////////////////////////////////////////////////////////////////////////////////////////
//
-(void)headerClicked:(id)sender
{
}
-(int)numberOfRowsInSection:(NSInteger)section
{
}
本文介绍如何使用UITableView实现分组数据的加载与显示,并通过按钮控制各组数据的显示与隐藏状态。代码中详细展示了如何初始化UITableView并设置数据源及代理方法,包括创建UITableViewCell、配置HeaderView等。
787

被折叠的 条评论
为什么被折叠?



