本文把 UITableView 兩個核心協定中最常使用的方法整理成速查表,方便開發時快速對照。
// 1. 右側索引值 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView // 2. 分組標題 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section // 3. 分組個數 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView // 4. 列數 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
5. 建立 cell(重用機制):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"reuse"; // 建立重用標識符
AddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) { // 若無可重用者才建立
cell = [[[AddressBookCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier] autorelease];
}
return cell;
}
// 6. 設定列是否可編輯
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
// 7. 點擊 edit 按鈕時觸發
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
// 8. 提交編輯操作時觸發
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
// 9. 是否允許移動
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
// 10. 提交移動之後觸發
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath
// 1. 設定列高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 55;
}
// 2. 選中 cell 時觸發
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
// 3. cell 的編輯樣式(插入/刪除)
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
// 4. 點擊編輯按鈕時顯示的文字(如「刪除」)
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"刪除";
}
// 5. 設定 cell 移動的目標位置
- (NSIndexPath *)tableView:(UITableView *)tableView
targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath