iOS UITableView(六) cell的移动

要想实现cell的移动  我们需要实现这几个方法

//系统自带的编辑按钮点击的时候会调用下面的方法 我们只需要重写一下就可以了(这个可用可不用)

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    //首先要调用父类的父类的方法知道如果改变 编辑按钮的状态Edit/Done

    [supersetEditing:editing animated:animated];

    //下面我们要通过这个编辑按钮来控制tableView的编辑

    [_tableViewsetEditing:editing animated:YES];

}

#pragma mark - 创建自定义的编辑按钮

- (void)creatCustomEdit {

    UIBarButtonItem *item = [[UIBarButtonItemalloc] initWithTitle:@"编辑"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(editClick:)];

    //作为右按钮

    self.navigationItem.rightBarButtonItem = item;

    [itemrelease];

}

- (void)editClick:(UIBarButtonItem *)item {

   if ([item.titleisEqualToString:@"编辑"]) {

        item.title =@"完成";

    }else {

        item.title =@"编辑";

    }

    //控制tableView的编辑状态

    //首先获取 当前tableView的编辑状态

   BOOL isEdit = _tableView.editing;

    //更改编辑状态

    [_tableViewsetEditing:!isEdit animated:YES];

}

#pragma mark - cell移动

//1.先设置 cell 是否可以移动

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

    //1区分不能移动

   if (indexPath.section ==1) {

       return NO;

    }

    return YES;

}

//2.正在移动cell的时候调用的函数

//只要正在移动那么就会调用下面的函数

//从原始的位置正在移动到目标的位置

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {

   /*

     sourceIndexPath00cell 的原始位置

     proposedDestinationIndexPath:移动cell将要移动到的目标位置

     */

    //禁止把其他分区的cell移动到第1分区

    //代码实现

   if (proposedDestinationIndexPath.section ==1) {

       return sourceIndexPath;//返回原来的位置

    }


   return proposedDestinationIndexPath;

    //返回值是移动到哪个位置

}

//3.移动cell完成之后调用的方法

//已经完成移动了

//在这个函数进行处理数据源数组

//一旦实现下面的方法那么在编辑模式下 cell 右侧就会出现一个移动的标志

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {

    NSLog(@"cell移动完成");

    //只要修改cell 那么数据源必须要同步

    

    //获取原cell的数据

    //要拥有绝对使用权

   UserModel *model = [_dataArr[sourceIndexPath.section][sourceIndexPath.row]retain];

    //从数据源中删除原来的cell的数据

    [_dataArr[sourceIndexPath.section]removeObject:model];

    

    //把原来的数据对象地址重新插入到 数据源数组的目标的位置

    [_dataArr[destinationIndexPath.sectioninsertObject:model atIndex:destinationIndexPath.row];

    //model 用完之后 要释放

    [model release];// release对应的是上面的retain(ARC除外)

    

    //刷新表格

    [tableViewreloadData];

}

通过这几个方法的实现就可以对cell进行移动



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值