UITableView的编辑和移动

上一篇记录了UITableView基本的用法,包括创建、设置代理以及代理方法的实现。这一篇来记录一下UITableView的编辑和移动。

编辑

因为数据的操作一般指的是增删改查,所以编辑操作一般值得是对数据的删除。

删除一般分为以下几步:

  1. 编辑当前页面为可编辑状态。注:即使当前页面为不可编辑状态,也可左滑拉出删除按钮。
  2. 确定可以编辑的行数。
  3. 确定编辑类型。
  4. 处理编辑事件。

* 编辑当前页面为可编辑状态

为了能够改变页面的编辑状态,我们在页面右上角加上一个按钮,用来改变页面的编辑状态。在此之前,我们要在storyboard中Controller对应的页面上包上一层Navigation。

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnAction:)];

按钮事件为:

- (void)rightBtnAction:(UIBarButtonItem *)sender
{
    if (self.tableView.editing == YES) {
        self.navigationItem.rightBarButtonItem.title = @"编辑";
    }else{
        self.navigationItem.rightBarButtonItem.title = @"完成";
    }
    self.tableView.editing = !self.tableView.editing;
}

* 确定可以编辑的行数

可以根据条件返回YES/NO。我们这里设置为全部可以编辑。

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

* 确定编辑类型

我们一般设置为删除。

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

* 处理编辑事件

在处理事件时,一定要注意数据和界面保持一致,否则会崩溃

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //该条数据是这个块中最后一条数据
    if ([[self.dataArray objectAtIndex:indexPath.section] count] == 1) {
        //删除数据
        [self.dataArray removeObjectAtIndex:indexPath.section];
        //更新页面
        NSIndexSet *set = [NSIndexSet indexSetWithIndex:indexPath.section];
        [self.tableView deleteSections:set withRowAnimation:UITableViewRowAnimationRight];
    }else{
        //删除数据
        [[self.dataArray objectAtIndex:indexPath.section] removeObjectAtIndex:indexPath.row];
        //更新页面
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
    }
}

移动

移动有跨块移动和不跨块移动,我这里把两种情况写在了一起。

同样的,移动也是分步骤的,步骤如下:

  1. 设置页面为编辑状态。
  2. 确定每行是否可以移动。
  3. 处理移动事件

* 设置页面为编辑状态

同编辑过程中的第一步

* 确定每行是否可以移动

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

* 处理移动事件

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSString *stringTemp = [[self.dataArray objectAtIndex:sourceIndexPath.section] objectAtIndex:sourceIndexPath.row];

    [[self.dataArray objectAtIndex:sourceIndexPath.section] removeObjectAtIndex:sourceIndexPath.row];
    [[self.dataArray objectAtIndex:destinationIndexPath.section] insertObject:stringTemp atIndex:destinationIndexPath.row];

    if ([[self.dataArray objectAtIndex:sourceIndexPath.section] count] == 0) {
        [self.dataArray removeObjectAtIndex:sourceIndexPath.section];
        [self.tableView reloadData];
    }
}

总结

在UITableView的操作中,唯一需要着重注意的就是数据要和视图一一对应,否则会造成UITableView的崩溃。