UITableView的建立與使用

2021-07-04 11:51:59 字數 2560 閱讀 6536

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,必須實現的**方法

//此方法返回每組單元格的個數(確定要建立多少單元格)

- (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section

//返回值為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

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

注意:如果是用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

由於**方法太多,這裡就不一一細說了,各位在使用的時候點進**方法看看,選擇自己需要的方法,主要是能靈活運用

iOS如何讓UITableView與導航欄緊密貼合

我們只需要將頭高度設定為0.1,尾高度設定為自己要的 必須設一下 再將頭檢視與尾檢視設定為空即可,效果如圖,是不是沒有縫隙呢?這個 的實現也很簡單,將下面 新增進去即可 uiview tableview uitableview tableview viewforheaderinsection nsi...

UITableView的詳細講解

1.uitableview的初始化 csharp view plain copy uitableview tableview uitableview alloc initwithframe cgrectmake 0,0,320,420 tableview setdelegate self table...

UITableView 索引的新增

1 自定義索引 準備資料,設計乙個陣列,陣列裡面的元素為每個section的陣列。返回section總數 nsinteger numberofsectionsintableview uitableview tableview 返回每個section的行數 nsinteger tableview ui...