TableView的添加删除执行顺序

来源:互联网 发布:雷洋死亡真相 知乎 编辑:程序博客网 时间:2024/06/06 01:05
1.我们要通过一个控件来控制tableView的编辑状态 进入或者退出编辑状态
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
   [super setEditing:editing animated:animated];
   [showTableView setEditing:editing animated:animated];
}
2第二步询问 tableView通过代理方法询问代理 他的每一行Cell是否都能编辑或者不能编辑 我们需要一个编辑状态 
#pragma mark———编辑: 添加和删除
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
3.当你的cell被设置成可以编辑状态时 tableView询问你 他到底是添加还是删除  前面都配置好啦 ,当我们点击添加或者删除按钮时,会执行代理方法commitEditingStyle:提交 ,根据tableView 返回样式editingStyle进行区分。
如果删除  如果添加insert



//添加和删除 都执行该代理方法
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//删除
if (editingStyle ==UITableViewCellEditingStyleDelete) {
NSMutableArray *array =[NSMutableArray arrayWithArray:[_dataArray objectAtIndex:indexPath.section]];
if([array count]>1)  {
//数据源操作
[array removeObjectAtIndex:indexPath.row];
[_dataArray replaceObjectAtIndex:indexPath.section withObject:array];
//Cell操作
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects: indexPath, nil] withRowAnimation:UITableRowAnimationLeft];
} else {
        [_dataArray removeObjectAtIndex:indexPath.section];
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
}

}
//添加
if  (editingStyle == UITableViewCellEditingStyleInsert) {
NSMutableArray *array = [NSMutableArray arrayWithArray:[_dataArray objectAtIndex:indexPath.section]];
[array addObject:@“北京”];
[_dataArray replaceObjectAtIndex:indexPath.section withObject:array];
NSIndexPath * insertIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:insertIndexPath, nil ]   withRowAnimation:UITableViewRowAnimationBottom];
 }
}

0 0