1.删除行
首先创建编辑按钮
UIBarButtonItem * right = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:(UIBarButtonItemStylePlain) target:self action:@selector(didClickRightBarButtonItemAction:)];
-(void)didClickRightBarButtonItemAction:(UIBarButtonItem *)button
{
NSLog(@"%@",button);
// _isEditing = !_isEditing;
if (_isEditing) {
NSLog(@"bianji = %d",_isEditing);
_isEditing = NO;//没有进入编辑状态
button.title = @"编辑";
}else{
NSLog(@"wanc = %d",_isEditing);
_isEditing = YES;//进入编辑状态
button.title = @"完成";
}
//tableView进入编辑状态
//默认所有的行都可以被编辑,编辑样式默认都是删除
[_listTableView setEditing:_isEditing animated:YES];
}
//是否可以编辑,当某一行可以删除时才出现
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
//当没有分区时编辑不执行
if (indexPath.section ==0) {
return NO;
}
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// NSLog(@"%s,%d",__FUNCTION__,__LINE__);
//修改数据源,即删除数据源中的某条数据
NSMutableArray * oneGoupArray = [_allGroupArray objectAtIndex:indexPath.section];
//如果删除某行cell,cell刚好是section最后一条数据时不再删除cell,直接删除section
if (oneGoupArray.count == 1) {
//删除section
NSLog(@"indexPath = %ld",indexPath.section);
[_allGroupArray removeObjectAtIndex:indexPath.section];
NSLog(@"indexPath2 = %ld",indexPath.section);
[_listTableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
NSLog(@"indexPath3 = %ld",indexPath.section);
}else{
[oneGoupArray removeObjectAtIndex:indexPath.row];
//tableview删除某行
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight];
}
}}