使用滑动手势删除tableview上的行

时间:2014-02-24 06:14:31

标签: objective-c uitableview xcode5 nsindexpath

我试图通过设置滑动手势然后使用IBAction调用删除执行滑动的行来绕过红色按钮删除(editingstyledelete)。应用程序崩溃,我收到错误: NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]

- (IBAction)deleteSwipe:(id)sender{
    [self deleteRow:self.tableView forCell:sender];
}

-(void) deleteRow:(UITableView *)tableView forCell:(UITableViewCell *)bCell{
    NSIndexPath *indexPath = [tableView indexPathForCell:bCell];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.queue removeObjectAtIndex:indexPath.row];
    [tableView reloadData];
}

我设置了断点异常,它指向:[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];,并在报告日志中指出索引路径值为nil。我之前使用过'deleteRowsAtIndexPaths'方法,但没有发现这个问题。

编辑:更新代码:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.queue removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView reloadData];
        }
}

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


}


-(BOOL) tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}


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

1 个答案:

答案 0 :(得分:5)

您可以通过实施以下UITableView deligate方法来实现此目的

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone; //if you don't want to show delete button
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
        return YES; // allow that row to swipe
        //return NO; // not allow that row to swipe
}

// Override to support editing/deleteing the table view cell on swipe.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleNone)
    {
        //--- your code for delete -----
    }
}