網路上關於左滑刪除的教學多到誇張,而且大量互相抄襲,把簡單的事情講得很複雜。實際上只要實作一個代理方法。
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// 刪除資料來源中的對應資料,self.cellData 是你自己的資料陣列
[self.cellData removeObjectAtIndex:indexPath.row];
// 刪除列表上的那一列
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
預設的刪除按鈕文字是 Delete,實作下面這個方法即可替換:
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
return @"刪除"; // 預設文字為 Delete
}
以下兩個代理方法有預設行為,不實作也一樣是「可以編輯、可以刪除」:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (BOOL)tableView:(UITableView *)tableView
canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
如果你看到這段錯誤:
'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)
意思是:你告訴 tableView 刪了一列,但資料來源還是 5 筆,兩邊數量對不上。原因通常是這兩行的順序寫反了。
正確順序是先刪資料,再刪 cell:
[self.cellData removeObjectAtIndex:indexPath.row]; ← 這行在前
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; ← 這行在後
另一個低級但常見的原因是忘了設代理:tableView.delegate = self;
若需要「刪除+置頂」等多個選項,iOS 8 之後可以實作:
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView
editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive
title:@"刪除"
handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
[self.cellData removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}];
return @[delete];
}
iOS 11 之後若想用系統內建的滑動樣式,則改用 trailingSwipeActionsConfigurationForRowAtIndexPath: 回傳 UISwipeActionsConfiguration,API 更簡潔,樣式也更貼近系統。