change Table to Edit mode and delete Rows inside a normal ViewController

后端 未结 2 846
清酒与你
清酒与你 2020-12-07 03:27

I just inserted a table into a normal UIViewController and connected the delegate and source components with the file\'s owner. Everything works fine when i insert data into

2条回答
  •  鱼传尺愫
    2020-12-07 03:41

    In order to enable edit mode for table view, you can call edit method on UITableView as,

    [self.tableView setEditing:YES animated:YES];
    

    You have to implement tableView:commitEditingStyle:forRowAtIndexPath: method to enable the deleting of rows. In order to delete the rows you need to use deleteRowsAtIndexPaths:withRowAnimation: method.

    For eg:-

    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];
      }   
    }
    

    For more details check the apple documentation here.

提交回复
热议问题