表視圖 UITableView 是以後應用開發中使用頻率極高的元件,必須熟练掌握。本文記錄了學習 UITableView 的初步心得,同時也順帶說明了經常搭配使用的 NSBundle 類。
簡單來說,NSBundle 本質上就是一個「路徑」。透過 [NSBundle mainBundle] 可以取得當前應用程式可執行文件所在的目錄,再配合 pathForResource:ofType: 方法,就能以「檔名 + 型別」的方式取得資源的完整路徑,進而存取該文件。
// 取得應用主 bundle 中某個 plist 文件的完整路徑 NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];
表視圖透過 delegate 與 dataSource 來驅動,以下是最常用的幾個方法:
// 1. 設置表的分組數量 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView // 2. 設置每個分組的行數 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section // 3. 為每個分區指定標題 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section // 4. 為每一行提供數據(cell) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath // 5. 建立右側索引欄 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
這幾個方法構成了 UITableView 的骨架:numberOfSectionsInTableView 決定有幾個分區,numberOfRowsInSection 決定每區有幾行,cellForRowAtIndexPath 則負責為每一行填充具體內容。三者搭配,就能渲染出完整的列表界面。而 NSBundle 則是我們讀取本地數據來源(如 plist 檔案)的重要工具,兩者相輔相成,是列表開發的基礎套路。