iOS tableView 左劃刪除功能

這幾天要實現左劃刪除的功能,發現網上很多帖子大多出自一人之手,然后都是 copy 的文章,其實都沒有那么復雜,只實現一個代理方法就可以了

- (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)

你把代理方法中這兩個方法順序搞混了,先刪除數據,再刪除 cell

[self.cellData removeObjectAtIndex:indexPath.row];這個方法在前

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];這個方法在后

還有就是,別2到沒設置代理,tableView.delegate = self;

過兩天寫自定義編輯多個 cell,選擇多個 cell 刪除,全選刪除,默認選擇按鈕為藍色,自定義選擇按鈕

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容