将表更改为编辑模式并删除普通ViewController中的行

Ale*_*Cio 4 uiviewcontroller tableview ios

我刚刚将一个表插入到普通的UIViewController中,并将委托和源组件与文件的所有者连接起来.当我将数据插入表行时,一切正常.但现在我想找出如何删除行.

我只看了很多其他帖子,但找不到合适的解决方案.

我试图为表中的每一行插入一个asseccory按钮:

cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
Run Code Online (Sandbox Code Playgroud)

我甚至找到了按下附件按钮时调用的方法:

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{

    NSLog(@"Accessory pressed");

    //[self tableView:tableView willBeginEditingRowAtIndexPath:indexPath];

    //[self tableView:nil canEditRowAtIndexPath:indexPath];
    //[self setEditing:YES animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

在日志中打印消息,但我尝试调用的方法(注释的方法)中没有一个确实将视图更改为编辑模式.我怎么解决这个问题?


这是UIViewController的屏幕截图.我还没有集成一个navigationController.

在此输入图像描述

iDe*_*Dev 10

为了启用表格视图的编辑模式,您可以调用编辑方法,UITableView因为,

[self.tableView setEditing:YES animated:YES];
Run Code Online (Sandbox Code Playgroud)

您必须实现tableView:commitEditingStyle:forRowAtIndexPath:方法以启用删除行.要删除行,您需要使用deleteRowsAtIndexPaths:withRowAnimation:方法.

例如: -

self.navigationItem.rightBarButtonItem = self.editButtonItem;//set in viewDidLoad

- (void)setEditing:(BOOL)editing animated:(BOOL)animated { //Implement this method
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { //implement the delegate method

  if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Update data source array here, something like [array removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  }   
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看此处Apple文档.