I'm assuming your table has just one section. You can extend this solution to multiple sections fairly easily.
- Add an NSMutableSet member "selectedRows" to your UIViewController subclass that manages your TableView
- in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
toggle the indexPath.row's membership in "selectedRows", like this:
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];
if ( [self.selectedRows containsObject:rowNsNum] )
[self.selectedRows removeObject:rowNsNum];
else
[self.selectedRows addObject:rowNsNum];
- indicate visually that a row is selected (e.g., set the cell's accessoryType property to UITableViewCellAccessoryCheckmark), or modify your cell visually in some other way to indicate that it is a selected row
- add a "delete" button to your UI, either in a table section header/footer, your title bar, anywhere, hooked up to a selector called "deleteRows"
- in your deleteRows method, iterate through the selectedRows set, building up an array of indexPaths, delete these rows from your data model, then call (with your preferred animation type):
[self.myTableView deleteRowsAtIndexPaths:arrayOfIndexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
EDIT:
Here's my full didSelectRowAtIndexPath method. The deselectRowAtIndexPath may be required for correct operation.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( self.editing )
return;
[self.myTableView deselectRowAtIndexPath:indexPath animated:YES];
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];
if ( [self.selectedRows containsObject:rowNsNum] )
[self.selectedRows removeObject:rowNsNum];
else
[self.selectedRows addObject:rowNsNum];
[self.myTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.2];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…