免费开源的iOS开发学习平台

UITableView详解:6-代理方法之编辑单元格

单元格Cell编辑方法

当希望对表视图中的单元格进行编辑时,因为涉及到对数据的修改,因此需要通过表视图的代理进行操作。在UITableViewDelegate协议中,定义了如下几个与单元格修改相关的方法,当需要对单元格进行修改时,会调用对应的方法。

  • 设置对单元格修改时添加的按钮及其对应的处理事件
- (nullable NSArray <UITableViewRowAction *>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath;
  • 开始编辑单元格前调用的方法
-(void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath ;
  • 完成编辑单元格后调用的方法
-(void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath;//完成编辑调用

UITableViewRowAction简单介绍

UITableViewRowAction对象是用于设置UITableViewCell处于编辑状态下所显示的按钮。默认情况下,左滑会显示一个删除按钮,我们也可以创建多个UITableViewRowAction对象从而实现不同的操作。

UITableViewRowAction对象的创建可以调用API中定义的类方法,在该方法中包含3个参数,分别是按钮的样式style、显示的标题title以及用户点击按钮后的操作handler。

+ (instancetype)rowActionWithStyle:(UITableViewRowActionStyle)style title:(nullable NSString *)title handler:(void (^)(UITableViewRowAction *action, NSIndexPath *indexPath))handler;

除此之外,UITableViewRowAction对象还可以设置它的背景颜色backgroundColor,其title属性也可以被修改。

@property (nonatomic, copy, nullable) NSString *title;
@property (nonatomic, copy, nullable) UIColor *backgroundColor; 

实现单元格编辑的基本步骤

当我们需要对单元格进行编辑时,可以按照如下的步骤进行实现。

  1. 实现editActionsForRowAtIndexPath:方法
  2. 创建UITableViewRowAction对象,并设置每个按钮对应的操作
  3. 调用reloadData方法刷新表格:对tableview的cell进行操作后,一定记得需要重新刷新表格,更新样式

下方的示例代码中,当修改某个单元格时,会显示3个按钮,分别是删除、移动和添加,当点击删除按钮后,该单元格对应的数据会被删除,表视图重新刷新显示。

- (nullable NSArray <UITableViewRowAction *>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"添加" handler:nil];
    UITableViewRowAction *action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"移动" handler:nil];
    UITableViewRowAction *action3 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NumberGroup *numberGroup = self.dataList[indexPath.section];
        NSLog(@"需要删除的单元格在第: %d 行",indexPath.row);
        [numberGroup.groupNumbers removeObjectAtIndex:indexPath.row];
        [tableView reloadData];
    }];
    NSArray *actionArray = @[action1,action2,action3];
    return actionArray;    
}

运行效果如下。当我们选择一个单元格向左滑动时,会出现3个操作按钮,当点击删除按钮时,会从dataList数组中删除掉选中的数据,并且打印出删除单元格的位置,最后调用reloadData方法,刷新表视图。

示例代码

https://github.com/99ios/8.2.6