UITableView分組,該例題分爲5個組,每一組有5行,每行內容爲當前組下標和行下標,有頭標題(HAHA),無尾標題。
顯示效果爲:
代碼如下:
#import "ViewController.h"
//遵守協議
@interface ViewController () <UITableViewDelegate,UITableViewDataSource>
//UITableView
@property (nonatomic,weak)UITableView * tableView;
//分組頭數據
@property (nonatomic,strong) NSMutableArray * sectionArray;
//strong ---數據類型
//weak ---控件之類的
@end
@implementation ViewController
- (void)viewDidLoad
{
[superviewDidLoad];
//加載數據
[self_loadData];
UITableView * table=[[UITableViewalloc]initWithFrame:CGRectMake(0,20, self.view.frame.size.width,self.view.frame.size.height-20)style:UITableViewStyleGrouped];
table.delegate=self;
table.dataSource=self;
self.tableView=table;
table.sectionFooterHeight=0; //如果有代理的話,此行沒有效果,以代理爲先
//table.sectionHeaderHeight=100;
[self.viewaddSubview:table];
}
#pragma mark - 加載數據
- (void) _loadData
{
NSArray * array=@[@"分組1",@"分組2",@"分組3",@"分組4",@"分組5"];
self.sectionArray=[NSMutableArrayarrayWithArray:array];
}
#pragma mark - UITableViewDatasource
//返回行數
- (NSInteger ) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return 3; //在該分組中有3行
//return (section+1)*2; //下標爲0的分組有2行
//下標爲1的分組有4行
//下標爲2的分組有6行
//下標爲3的分組有8行
returnself.sectionArray.count;
}
//返回cell
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * identy=@"table";
UITableViewCell * cell=[tableViewdequeueReusableCellWithIdentifier:identy];
if (!cell)
{
cell=[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:identy];
}
cell.textLabel.text = [NSStringstringWithFormat:@"%li %li",indexPath.section,indexPath.row]; //打印分組和行數
return cell;
}
#pragma mark - 返回分組數量
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
returnself.sectionArray.count; //分組數組長度
//return 4; //分組有4組
}
#pragma mark - UITableViewDelegate
//設置分組的頭標題
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return@"haha";
}
//設置分組的尾標題
//- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
//{
// return @"hello world";
//}
#pragma mark - 自定義頭部
//- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
// UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
// view.backgroundColor=[UIColor redColor];
// return view;
//}
#pragma mark - 自定義尾部
//- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
// UIView * view=[[UIView alloc]init];
// view.backgroundColor=[UIColor blueColor];
// return view;
//}
#pragma mark - 設置頭部的高度
- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
return 50;
}
#pragma mark - 設置尾部的高度
//- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section
//{
// return 30;
//}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
@end