tableView 刪除cell時的注意點

刪除cell,首先要使用代理方法:app

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;

}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        //這裏的deleteRowData是我本身的方法,用來刪除相應數據的,
        if ([self deleteRowData:indexPath.row]) {
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            //tableView必需要更新,不然報錯
            [self.tableView reloadData];
        }
        
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

接下來要注意的是,在最後一個代理方法裏,你要先刪除數據(datasource),再執行動畫,再更新數據。這個順序不能亂,網上不少教程裏沒有提到這個細節。ide

相關文章
相關標籤/搜索