select multiple rows from uitableview and delete

前端 未结 2 1906
旧时难觅i
旧时难觅i 2020-12-09 14:29

i am displaying a list of items in a tableview.i need to select and delete multiple rows from the table at a time,any resources on how to do this

2条回答
  •  一个人的身影
    2020-12-09 15:06

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

提交回复
热议问题