TableView 的每一列外觀幾乎一模一樣,不同的只有資料。若每次都重新建立 cell,捲動時會明顯卡頓,因此 iOS 提供了一套「重用」機制。
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"CellTable";
// 先向緩衝池索取
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 池子裡沒有,才真的建立
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:ID];
}
return cell;
}
這段寫法的意義是:畫面上同時最多只有十幾個 cell 存在,其餘的都躺在重用池裡。identifier 必須在每個 reuseIdentifier 對應的樣式上保持一致,否則會取到錯誤外觀的 cell。
cell.accessoryType = UITableViewCellAccessoryCheckmark;
accessoryType 除了 Checkmark,還有 DisclosureIndicator(灰色箭頭,表示可進入下一層)與 DetailButton(藍色 i 字,表示可看更多資訊)。這三種是列表介面裡最常見的視覺語彙,能省下不少自製元件的工夫。
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView deleteRowsAtIndexPaths:self.indexPaths
withRowAnimation:UITableViewRowAnimationLeft];
deleteRowsAtIndexPaths 不只是播放一個動畫而已,它同時會告訴表格「資料少了一筆」。因此呼叫之前必須先把對應資料從 array 中移除,兩邊不同步就會直接崩潰。
下面是一個能點擊切換勾選狀態的實作,同時示範了資料源與代理的分工。
// CSZViewController.h
@interface CSZViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)trashClick:(id)sender;
@end
// CSZViewController.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"CellTable";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:ID];
}
cell.textLabel.text = self.array[indexPath.row];
cell.detailTextLabel.text = @"description....";
if ([self.deleteArr containsObject:cell.textLabel.text]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *text = self.array[indexPath.row];
if ([self.deleteArr containsObject:text]) {
[self.deleteArr removeObject:text];
[self.indexPaths removeObject:indexPath];
} else {
[self.deleteArr addObject:text];
[self.indexPaths addObject:indexPath];
}
// 只重繪這一列,效能遠優於 reloadData
[tableView reloadRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationLeft];
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 70;
}
這裡有兩個值得學的習慣。第一,勾選狀態存在 deleteArr 這個獨立集合中,而不是去讀 cell 的視覺狀態——cell 會被重用,把狀態存在 cell 上遲早出錯。第二,更新時只 reload 那一列,而不是整張表 reloadData,這在長列表上差距很明顯。