How to delete cells from a table view?
I have an Edit button in my navigation bar, and I have an table view.
My edit button calls an -editAction method.
And then, I have this piece of code to delete a cell, but I don't know how I can make the edit button to call this code...or how the edit button can let the table view display those red delete circles for every cell, which then trigger this:
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the managed object at the given index path
NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
[managedObjectContext deleteObject:eventToDelete];
// Update Event objects array and table view
[eventsArray removeObject开发者_JAVA百科AtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
// Commit the change
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error
}
}
}
According to the UITableView
class reference docs, the code:
tableView.editing = YES;
Should put the table into editing mode and display those red delete circles. Then when the user deletes a cell your data source method should be called.
You can also use [tableView setEditing:YES animated:YES];
for an animated effect
In your view controller's -viewDidLoad method add the Edit button:
self.navigationItem.rightBarButtonItem = self.editButtonItem;
This button will toggle the controller's editing mode, sending it -setEditing:animated:
精彩评论