UITableView 是 iOS 中最常用的清單元件。本文系統性地整理它的協定、常用方法、屬性與效能優化技巧。
UITableView 是 UIScrollView 的子類,因此天生就能響應滾動事件。要使用它,需要讓控制器實作 UITableViewDataSource 協定;或直接繼承 UITableViewController(它已內建實作 DataSource 與 Delegate 協定)。
// 每一組顯示多少列 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section // 每一列顯示什麼內容(僅可視範圍內的 cell 會被建立,滾出視野後會自動釋放) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
記得在 viewDidLoad 中把 dataSource 與控制器關聯起來:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.dataSource = self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; // 分組數,預設 1 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section; - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView; // 右側索引條
局部刷新與重新載入:
// 局部刷新某一列 NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:0]; [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationBottom]; // 重新載入全部資料(可用於載入更多) [self.tableView reloadData];
self.tableView.delegate = self;
// 自訂每列高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
// 某一列被選中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = indexPath.row;
}
// 開始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
// 自訂每組的頭部視圖
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
self.tableView.tableHeaderView = [UIButton buttonWithType:UIButtonTypeContactAdd]; // 頭部控件 self.tableView.tableFooterView = [[UISwitch alloc] init]; // 尾部控件 self.tableView.rowHeight = 60; // 統一列高 self.tableView.sectionHeaderHeight = 44; // 每組頭高 self.tableView.backgroundView = nil; self.tableView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1]; self.tableView.allowsSelection = NO; // 禁止選中
由於螢幕上任何時刻只有可見範圍的 cell 存在,我們應透過「重用」來反覆利用 cell,避免頻繁配置與釋放:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"hero";
// 1. 從重用池中取出可循環利用的 cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 2. 若無可重用者,才建立新的
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:ID];
}
// 3. 設定新資料
Hero *hero = self.heros[indexPath.row];
cell.textLabel.text = hero.name;
cell.detailTextLabel.text = hero.intro;
cell.imageView.image = [UIImage imageNamed:hero.icon];
return cell;
}
此外,實務經驗顯示:使用自訂的 UITableViewCell 子類,往往比直接使用系統預設樣式更能維持流暢的滾動效能。
從介面設計工具拖入的預設是「動態 Cell」。若切換為「靜態 Cell」,就能直接在 cell 上拖放控件、自訂每一列的樣式,適合表單類、結構固定的畫面。