UITableView的添加、删除、移动操作

#pragma mark -----表视图的移动操作-----

//移动的第一步也是需要将表视图的编辑状态打开
//2、指定哪些行可以进行移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    //默认都可以移动
    return YES;
}

//3、移动完成之后要做什么事,怎么完成移动
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    //先记录原有位置下的模型数据
    Student *student = _dataArray[sourceIndexPath.row];
    [student retain];
    
    //删除原位置下的模型数据
    [_dataArray removeObjectAtIndex:sourceIndexPath.row];
    
    //在新位置将记录的模型数据添加到数据数组中
    [_dataArray insertObject:student atIndex:destinationIndexPath.row];
    
    [student release];
}


#pragma mark -----删除、添加数据-----

//1、让将要执行删除、添加操作的表视图处于编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    //先执行父类中的这个方法。
    [super setEditing:editing animated:animated];
    
    
    //表视图执行此方法
    [self.tableView setEditing:editing animated:animated];
}

//2、指定表示图中哪些行可以处于编辑状态
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.row % 2 == 0) {
//        return YES;
//    } else {
//        return NO;
//    }
    //默认全部行都可以编辑
    return YES;
}

//3、指定编辑样式,到底是删除还是添加  delegate协议里面
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    //此方法如果不重写,默认是删除样式
//    return UITableViewCellEditingStyleDelete;
    return UITableViewCellEditingStyleInsert;
}

//不管是删除还是添加,这个方法才是操作的核心方法,当点击删除、或者添加按钮时,需要做什么事情,怎样才能完成删除或者添加操作,全部在这个方法内部指定。
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView beginUpdates];//表视图开始更新
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //将该位置下的单元格删除
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        //删除数据数组中与该单元格绑定的数据
        [_dataArray removeObjectAtIndex:indexPath.row];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        Student *student = _dataArray[indexPath.row];
        
        //构建一个位置信息
        NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
        
        [tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationTop];
        [_dataArray insertObject:student atIndex:index.row
         ];
    }
    
    
    
    
    [tableView endUpdates];//表视图结束更新
 }

 

posted @ 2016-02-22 14:42  _Mo  阅读(418)  评论(0编辑  收藏  举报