表視圖(UITableView)大概是 iOS 開發裡出現頻率最高的元件。通訊錄、頻道列表、設定畫面,幾乎所有需要條列大量資料的場合都會用到它。除了最基本的一列一列的呈現方式,表視圖還支援分段、分組、索引,甚至能透過「細節展示」機制做多層次的資料呈現,可以說一表勝千言。
表視圖的 API 相對其他控制項要複雜一些,但只要掌握幾個關鍵方法,多數場景都能應付自如,這份投入絕對值得。
本文要動手做的是最基礎的「簡單表視圖」,屬於動態表。順帶一提,在 iOS 5 之前並沒有靜態表的概念,當時所有的表都是動態的。
iOS 5 之後,我們可以透過 xib 或 Storyboard 來設計表視圖。若只是想顯示最單純的表,其實只要實作 UITableViewDataSource 協議中兩個必要方法即可:
tableView:numberOfRowsInSection::回報每一段(section)裡有幾列。tableView:cellForRowAtIndexPath::提供特定列的儲存格內容。實作步驟如下:
另外要留意:構造方法 initWithFrame:style: 是在程式碼建立表視圖時呼叫;若改用 xib 或 Storyboard,表視圖會在控制器被實例化的階段一併建立。表視圖顯示時會送出 numberOfRowsInSection: 詢問列數,儲存格要顯示時則送出 cellForRowAtIndexPath: 索取資料。
若完全用程式碼建立儲存格,記得把 Prototype Cells 數量設為 0:
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
這裡的 Identifier 就是「可重用儲存格識別碼」,概念與 Collection View 的可重用元件相同:先向表視圖詢問有沒有可回收的儲存格,沒有的話才真的配置一個新物件。列表滾動時能重複使用同一批儲存格,是表視圖保持順順的前提。
如果改用 Storyboard 設計儲存格外觀,只要選取 Table View Cell,在屬性檢查器的 Style 中挑選樣式,並填入 Identifier。這樣一來程式碼裡就不必再自行 new 出儲存格,直接以識別碼取用即可。
接著把 team.plist 與球隊圖片加入專案。ViewController.h 看起來會像這樣:
#import <UIKit/UIKit.h> @interface ViewController : UITableViewController @property (nonatomic, strong) NSArray *listTeams; @end
listTeams 用來承裝從檔案讀出的資料,讀取動作放在 viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"team" ofType:@"plist"];
// 取出屬性列表檔中的全部資料
self.listTeams = [[NSArray alloc] initWithContentsOfFile:plistPath];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listTeams count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
NSUInteger row = [indexPath row];
NSDictionary *rowDict = [self.listTeams objectAtIndex:row];
cell.textLabel.text = [rowDict objectForKey:@"name"];
NSString *imagePath = [rowDict objectForKey:@"image"];
imagePath = [imagePath stringByAppendingString:@".png"];
cell.imageView.image = [UIImage imageNamed:imagePath];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
因為這個表只有一段,numberOfRowsInSection: 直接回傳 listTeams 的數量即可。indexPath 的 row 就是目前的列索引,而 accessoryType 則決定儲存格右側要顯示哪種附屬圖示,這裡用的是熟悉的灰色箭頭。
UITableViewCellStyleDefault 之外還有三種樣式可選,把它替換掉再跑一次,就能實際比較標題、副標題與圖片排列上的差異,這也是理解儲存格樣式最快的方式。