UITableView 幾乎是所有 iOS 應用都會用到的元件,聯絡簿、設定頁、新聞列表,背後都是它。理解它的結構與兩個關鍵協定,是每個 iOS 開發者的必修課。
TableView 本質上是一個可滾動的視圖,它被切分成一個個 section(區段),每個 section 又由若干 row(列)組成,而每一列就是一個 UITableViewCell 的實例。你可以往 cell 裡塞圖片、文字或任何自訂檢視,也能自訂高度、樣式、分組方式與附件檢視。這些行為分別由 UITableViewDelegate 與 UITableViewDataSource 兩個協定來定義。
#import <UIKit/UIKit.h>
@interface TableViewController : UIViewController
@property (nonatomic, strong) UITableView *myTableView;
@end
@implementation TableViewController
@synthesize myTableView;
- (void)viewDidLoad {
[super viewDidLoad];
self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds
style:UITableViewStylePlain];
[self.view addSubview:self.myTableView];
}
@end
初始化時的 style 有兩種常見選擇:
UITableViewStylePlain:沒有背景圖的素面列表,最常用。UITableViewStyleGrouped:帶背景紋理與圓角分組邊框,也就是 iOS「設定」App 的外觀。列高由 delegate 決定,記得先把 delegate 接上:
- (void)viewDidLoad {
[super viewDidLoad];
CGRect tableViewFrame = self.view.bounds;
self.myTableView = [[UITableView alloc] initWithFrame:tableViewFrame
style:UITableViewStylePlain];
self.myTableView.delegate = self;
[self.view addSubview:self.myTableView];
}
- (void)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat result = 20.0f;
if ([tableView isEqual:self.myTableView]) {
result = 40.0f;
}
return result;
}
這裡的 NSIndexPath 是理解 TableView 的關鍵:它由 section 與 row 兩個索引組成,兩者都從 0 開始,因此「第一個區段的第一列」就是 (0, 0)。
要讓列表有內容,還必須遵循 UITableViewDataSource 協定,實作三個方法:回報區段數、回報每區段的列數、以及提供每一列的 cell。
self.myTableView.dataSource = self;
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger result = 0;
if ([tableView isEqual:self.myTableView]) {
result = 3;
}
return result;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
NSInteger result = 0;
if ([tableView isEqual:self.myTableView]) {
switch (section) {
case 0: result = 3; break;
case 1: result = 5; break;
case 2: result = 8; break;
}
}
return result;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *result = nil;
if ([tableView isEqual:self.myTableView]) {
static NSString *TableViewCellIdentifier = @"MyCells";
result = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
if (result == nil) {
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:TableViewCellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld",
(long)indexPath.section, (long)indexPath.row];
}
return result;
}
這段程式碼裡最重要的是 dequeueReusableCellWithIdentifier:。TableView 只會保留螢幕上看得見的少數 cell,捲出畫面的 cell 會被回收再利用。如果每次都 new 一個新 cell,長列表會迅速吃光記憶體。這是 TableView 高效能的秘密所在。
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([tableView isEqual:self.myTableView]) {
NSLog(@"%@", [NSString stringWithFormat:
@"Cell %ld in Section %ld is Selected",
(long)indexPath.row, (long)indexPath.section]);
}
}
除了系統提供的附件樣式,例如:
result.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
你也可以放任意自訂檢視進去,做法是把按鈕之類的元件指派給 accessoryView:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *result = nil;
static NSString *myCellIdentifier = @"SimpleCell";
result = [tableView dequeueReusableCellWithIdentifier:myCellIdentifier];
if (result == nil) {
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:myCellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld",
(long)indexPath.section, (long)indexPath.row];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0.0f, 0.0f, 150.0f, 25.0f);
[button setTitle:@"展開" forState:UIControlStateNormal];
[button addTarget:self
action:@selector(performExpand:)
forControlEvents:UIControlEventTouchUpInside];
result.accessoryView = button;
return result;
}
按下按鈕後,由於 cell 沒有直接持有 index path,必須反向查詢:
- (void)performExpand:(id)paramSender {
/* 在這裡實作你的行為 */
UITableViewCell *ownerCell = (UITableViewCell *)paramSender.superview;
if (ownerCell != nil) {
NSIndexPath *ownerCellIndexPath = [self.myTableView indexPathForCell:ownerCell];
NSLog(@"附件被點擊,indexPath = %@", ownerCellIndexPath);
if (ownerCellIndexPath.section == 0 && ownerCellIndexPath.row == 1) {
/* 第一個區段的第二列 */
}
}
}
把觀念整理成一句話:TableView 只負責「怎麼排」,資料怎麼來、cell 長什麼樣、點了之後做什麼,全都在 delegate 與 dataSource 這兩個協定裡。掌握 cell 重用機制與 NSIndexPath 這兩個概念,之後無論是自訂 cell、下拉更新還是巢狀列表,都只是同樣規則的延伸。若你使用新的 iOS 版本開發,也可以考慮 UITableViewDiffableDataSource,它把資料更新與動畫同步化,能省下大量手動管理 index path 的工夫。