iOS 多选删除功能附tableViewTips及单选删除

2020-01-20 13:11:03于丽

一、前言

这次分享并记录一下tableView的多选删除,并额外记录一下单选删除及tableView的设置小技巧。

二、想要实现的效果图如下:

1、先上原图

ios,多选删除,tableViewTips

2、然后编辑图如下:

ios,多选删除,tableViewTips

3、编辑步骤:

点击右上角按钮编辑,界面呈现编辑状态底部删除按钮弹出

选择删除cell项,点击右下角删除可删除

点击右上角,退出编辑状态,底部删除按钮退出界面

三、多选删除核心代码

1、设置允许tableView编辑状态下允许多选


_mainTableView.allowsMultipleSelectionDuringEditing = YES;

2、将cell设置为可选择的风格(下面代码是在自定义Cell内部)


self.selectionStyle = UITableViewCellSelectionStyleDefault;

说明:因为自认为系统的选中状态很难看,所以在cell的基类里已经把 selectionStyle 设置为None,但是想要多选必须将其打开,大家切记。

3、不喜欢系统的选中状态,可更改选中状态的背景(下面也是在自定义cell内部)


 UIView *view = [[UIView alloc] init];
 view.backgroundColor = UIColorFromRGB(0xF6F6F6);
 self.selectedBackgroundView = view;

4、右上角点击事件


 [self.viewModel.rightViewModel.clickSubject subscribeNext:^(id x) {
    @strongify(self);
    if (self.mainTableView.editing) {
      self.viewModel.rightViewModel.title = @"编辑";
      [UIView animateWithDuration:0.5 animations:^{
        [self.mainTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
          @strongify(self);
          make.edges.equalTo(self);
        }];
      }];
    } else {
      self.viewModel.rightViewModel.title = @"确定";
      [UIView animateWithDuration:0.5 animations:^{
        [self.mainTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
          @strongify(self);
          make.left.right.top.equalTo(self);
          make.bottom.equalTo(-50);
        }];
      }];
    }
    [self.mainTableView setEditing:!self.mainTableView.editing animated:YES];
  }];

5、右下角删除事件


 [[[self.deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
     @strongify(self);
    NSMutableArray *deleteArray = [NSMutableArray array];
    for (NSIndexPath *indexPath in self.mainTableView.indexPathsForSelectedRows) {
      [deleteArray addObject:self.viewModel.dataArray[indexPath.row]];
    }
    NSMutableArray *currentArray = self.viewModel.dataArray;
    [currentArray removeObjectsInArray:deleteArray];
    self.viewModel.dataArray = currentArray;
    [self.mainTableView deleteRowsAtIndexPaths:self.mainTableView.indexPathsForSelectedRows withRowAnimation:UITableViewRowAnimationLeft];//删除对应数据的cell
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
      @strongify(self);
      [self.mainTableView reloadData];
    });
  }];