tableview之多行删除

本文介绍了如何在UITableView中实现多行删除功能。包括删除所有选定的cell、非编辑状态下滑动删除以及在多选模式下点击确定后的批量删除。提供了关键代码示例,涉及删除数据源和更新表格视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

删除所有的cell:

//找到所有的indexPath

     NSArray *arr = [self.tableView indexPathsForRowsInRect:CGRectMake(0, 0, self.view.frame.size.width, self.tableView.contentSize.height)];
    
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [self.tableView selectRowAtIndexPath:obj animated:YES scrollPosition:UITableViewScrollPositionNone];

    }];


//拿到现在是选择状态的indexP数组。。
    /*
     **这个属性方便了太多!
     */
    NSArray *arr = self.tableView.indexPathsForSelectedRows;
    //此处从数组删除注意:按照arr 顺序删除会造成越界崩溃、、
    
    NSMutableIndexSet *set = [NSMutableIndexSet indexSet];
    for (NSIndexPath *indexP in arr) {
        [set addIndex:indexP.row];
    }

    
    [self.dataArr removeObjectsAtIndexes:set];
    
    
    
    [self.tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];

二.在cell处于非编辑状态的时候 滑动删除:

1,首先允许用户编辑:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

    return YES;
}

2, 滑动点击删除按钮后执行这个方法:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [self.dataArr removeObjectAtIndex:indexPath.row];
        [self.tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

三.在多选状态下点击选择的cell之后  点击确定按钮之后执行:

-(IBAction)shureAction:(id)sender{
    //拿到现在是选择状态的indexP数组。。
    /*
     **这个属性方便了太多!
     */
    NSArray *arr = self.tableView.indexPathsForSelectedRows;
    //此处从数组删除注意:按照arr 顺序删除会造成越界崩溃、、
    
    NSMutableIndexSet *set = [NSMutableIndexSet indexSet];
    for (NSIndexPath *indexP in arr) {
        [set addIndex:indexP.row];
    }

    
    [self.dataArr removeObjectsAtIndexes:set];
    
    
    
    [self.tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];

//    [self.tableView reloadData];
    
    
    NSLog(@"seleteArr = %@",arr);
    
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值