1. 程式人生 > >UITableView的建立與使用

UITableView的建立與使用

1,表檢視的建立

表檢視可以用UITableViewController來建立,表格控制器預設的根檢視就是一個表檢視
這裡主要介紹表檢視在檢視控制器(ViewController)中建立,建立方法:
UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, 375, 647) style:UITableViewStyleGrouped];
//設定代理 
tableView.delegate = self;
tableView.dataSource = self;
//新增到當前檢視上    
[self.view addSubview:tableView];
表檢視初始化的時候,樣式有兩種,平鋪樣式和分組樣式UITableViewStyleGrouped分組樣式 UITableViewStylePlain平鋪樣式 2,必須實現的代理方法<UITableViewDelegate,UITableViewDataSource>
//此方法返回每組單元格的個數(確定要建立多少單元格)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{    
    return fontNames.count;
}
//返回值為cell,此代理方法是用來建立單元格
引數indexPath有兩個屬性:
indexPath.section表示是哪一組
indexPath.row表示是哪一行
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //建立單元格
}

3,建立單元格cell的方法

在建立單元格的時候有兩種方法建立:(1)從閒置池去單元格,起到懶載入作用.(2)註冊單元格

<1>,從閒置池取單元格(當閒置池有空閒的單元格的時候,就從閒置池取,閒置池沒有的時候再建立單元格)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];   
    }
    NSArray *fontNames=[dataList objectAtIndex:indexPath.section];
    NSString *font=[fontNames objectAtIndex:indexPath.row];
    cell.textLabel.text=font;
    cell.textLabel.font=[UIFont fontWithName:font size:20];
    return cell;
}
<2>註冊單元格(在建立的時候就註冊,不在代理方法裡註冊)

 //這句程式碼是在建立之後寫的,不是在代理方法中寫
[tableView registerClass:[UITableViewCell class]forCellReuseIdentifier:@"cell"];

 //在代理方法中直接取單元格,不需要建立
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"" forIndexPath:indexPath];
   NSArray *fontNames=[dataList objectAtIndex:indexPath.section];
   NSString *font=[fontNames objectAtIndex:indexPath.row];
   cell.textLabel.text=font;
   cell.textLabel.font=[UIFont fontWithName:font size:20];
   return cell;
}

注意:如果是用xib檔案畫出來的單元格時,註冊要用下面的方法

[tableView registerNib:[UINib nibWithNibName:@"NIbCell" bundle:nil] forCellReuseIdentifier:iden];

3,設定單元格的高度,兩種方法
//(1),直接在建立tableView的時候用tableView來設定
tableView.rowHeight = 100;
//2,用tableView的代理方法設定單元格的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath




4,常用的代理方法
//此方法是設定每一組的組標題,有多少組就呼叫多少次
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
   NSString *headerTitle=[NSString stringWithFormat:@"第%ld組",section+1];
   return headerTitle;
}
由於代理方法太多,這裡就不一一細說了,各位在使用的時候點進代理方法看看,選擇自己需要的方法,主要是能靈活運用