原文地址: http://blog.sina.com.cn/s/blog_7e3132ca0100wyls.html
在XCode對應頭文件中修改該類所繼承的父類:@interface TableViewController:UIViewController <UITableViewDataSource, UITableViewDelegate>
{
}
{
}
在對應的.m文件中添加如下代碼:
@implementation TableViewController
{
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,320,460) style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,320,460) style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
}
這樣就在view上添加了一個tableView,但其樣式是默認的,其中的內容也是空白的,而且此時是無法運行的,因為在頭文件中添加了UITableViewDataSource和UITableViewDelegate兩個類,所以必須設置一些自定義tableView樣式的方法,下面列舉了一些相關的方法:
設置Cell高度:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
設置SectionHeader高度:
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
設置SectionFooter高度:
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
設置Section數目:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
設置SectionHeader內容:
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
設置各個Section中的Cell個數:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
設置Cell內容:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
設置Cell行縮進量:
-(NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
設置Cell被選中響應前動作(例如:可用以判斷選中的Cell,來阻止其響應)
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
設置Cell選中觸發響應:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath