標籤:
之前兩篇部落格簡單學習了Picker view控制項的使用,接下來再學習IOS應用中很重要的一個視圖--表視圖。
在表視圖中,每個表視圖都是UITableView的一個執行個體,每個可見行都是UITableViewCell的一個執行個體。
表視圖有兩種基本格式,分組的表和普通表,普通表可以實現索引,實現了索引的表成為索引表。(PS.技術上,分組表也可以實現索引,不過好像蘋果的設計規範中不支援)
一個簡單的表視圖應用介面設計:
向storyboard中拖一個table view控制項,他會自動佔滿螢幕,至於約束,可以自己建立,記得設定tableview的tag為1,後面會用到。
table view的outlets中會有dataSource和delegate兩個設定項,按住每個設定項後面的空心圓,拖向storyboard中的controller按鈕,完成關聯。
代碼講解:
首先要在對應控制器的.h檔案中實現UITableViewDataSource和UITableViewDelegate兩個協議。
在.m檔案中首先定義一個nsarray類型的屬性,這個屬性用來存放tableview要顯示的資料,並且在viewDidLoad方法中給nsarray賦值。
在viewDidLoad方法中還需要做的是把tableview的頂部向下位移一定數量來美化介面(算不得美化,如果不做這一步處理,tableview頂部會緊挨著狀態列,很難看<( ̄▽ ̄)> 哇哈哈…)
UITableView* tableView = (id)[self.view viewWithTag:1];//通過tag擷取控制項 UIEdgeInsets contentInset = tableView.contentInset; contentInset.top = 20; [tableView setContentInset:contentInset];
然後實現兩個委託方法,一個是- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section,返回這個table的行數,
另一個是- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath,這個方法會返回指定行的TableViewCell。
首先看看這個方法的參數,第一個參數是一個tableview,表示觸發這個方法的table。第二個參數是NSIndexPath類型的值,這個類型有兩個主要的屬性,section和row,組和行。
建立一個UITableViewCell對象,此處使用的dequeueReusableCellWithIdentifier:方法,這個方法會返回一個可以重用的cell,也有可能返回nil
所以我們要判斷傳回值,如果傳回值為nil,就需要執行個體化一個cell
有了cell,就能設定cell要顯示的文本
cell.textLabel.text = self.dwarves[indexPath.row];
完整代碼:
1 // 2 // ViewController.m 3 // Simple Table 4 // 5 // Created by 張光發 on 15/10/19. 6 // Copyright (c) 2015年 張光發. All rights reserved. 7 // 8 9 #import "ViewController.h"10 11 @interface ViewController ()12 @property (strong, nonatomic) NSArray* dwarves;13 @end14 15 @implementation ViewController16 17 - (void)viewDidLoad18 {19 [super viewDidLoad];20 self.dwarves = @[ @"Sleepy", @"Sneezy", @"Bashful", @"Happy", @"Doc", @"Grumpy", @"Dopey", @"Thorin", @"Dorin", @"Nori", @"Ori", @"Balin", @"Dwalin", @"Fili", @"Kili", @"Oin", @"Gloin", @"Bifur", @"Bofur", @"Bombur" ];21 UITableView* tableView = (id)[self.view viewWithTag:1];22 UIEdgeInsets contentInset = tableView.contentInset;23 contentInset.top = 20;24 [tableView setContentInset:contentInset];25 }26 27 - (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section28 {29 return [self.dwarves count];30 }31 32 - (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath33 {34 static NSString* SimpleTableIndetifier = @"SimpleTableIdentfier";35 UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIndetifier];36 if (cell == nil) {37 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIndetifier];38 }39 cell.textLabel.text = self.dwarves[indexPath.row];40 return cell;41 }42 43 @endView Code
IOS中Table View控制項練習