.h设置协议
#import <UIKit/UIKit.h>
@interface ZYTestViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,retain)UITableView *tab;
@end
.m代码
#import "ZYTestViewController.h"
@interface ZYTestViewController ()
@end
@implementation ZYTestViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_tab=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tab.delegate=self;
_tab.dataSource=self;
//设置单元格的行高,在此设置会导致所有的行高都为80
_tab.rowHeight=80;
[self.view addSubview:_tab];
}
//方法的返回值就是设置这个表有多少个区的,默认是1个区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
//设置特定的行高,当两者都设置时,以此为准
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 40;
}
//设置某个区的行数,方法有两个参数,第一个参数就是设置委托的表,第二个参数就是要设置的是哪个区,此方法的返回值表示要设置这个区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 5*(section+1);
}
//设置区头标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [NSString stringWithFormat:@"第%d区",section];
}
//设置区头的高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//设置一个重用标示符
static NSString *cellIndentifier=@"cell";
//每次代码执行的时候先从tableView的重用队列里面去寻找有没有可以重复使用的单元格
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
//如果没有找到可以重用的单元格,那么就去创建单元格
if(!cell){
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIndentifier]autorelease];
//把每个单元格共有的东西放在此处
cell.detailTextLabel.text=@"你好";
cell.imageView.image=[UIImage imageNamed:@"c_item0.jpg"];
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
//设置单元格选择样式
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
//把每个单元格不同的东西放在此处
cell.textLabel.text=[NSString stringWithFormat:@"第%d区,第%d行",indexPath.section,indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%d---%d",indexPath.section,indexPath.row);
}