您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UITableView 左滑刪除:一個代理方法就搞定

編輯:iOS 開發綜合

網路上關於左滑刪除的教學多到誇張,而且大量互相抄襲,把簡單的事情講得很複雜。實際上只要實作一個代理方法。

核心程式碼

- (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」改成中文

預設的刪除按鈕文字是 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

如果你看到這段錯誤:

'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 更簡潔,樣式也更貼近系統。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved