前面我已经写过cell删除的博客感觉不太全面,今天我们来总结一下cell的删除几种方法
在应用里大概会用到3种cell的删除方式
1、向左划cell,右侧出现删除按钮
//设置编辑的风格
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
//改变删除按钮的title
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"删除";
}
//删除用到的方法
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
//删除数组里的数据
[self.arrayValue removeObjectAtIndex:[indexPath row]];
//删除对应数据的cell
[tableview deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
2、在导航栏上加个删除按键
就像之前写的一样 只要让tableview可以编辑就会出现删除按钮
UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:selfaction:@selector(deleteAction)];
-(void)deleteAction
{
[self.tableview setEditing:!self.tableview.editing animated:YES];
if (self.tableview.editing)
{
[self.navigationItem.leftBarButtonItem setTitle:@"删除"];
}
else
{
[self.navigationItem.leftBarButtonItem setTitle:@"编辑"];
}
}
3、批量删除(此方法来自前辈冷胜任的博客)
deleteDic = [[NSMutableDictionary alloc]init];
UIBarButtonItem *delBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:selfaction:@selector(deletebtnClick)];
UIBarButtonItem *editBtn = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:selfaction:@selector(editbtnClick)];
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
//删除按钮
-(void)deletebtnClick
{
[array removeObjectsInArray:[deleteDic allKeys]];
[array writeToFile:Path atomically:YES];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithArray:[deleteDic allValues]] withRowAnimation:UITableViewRowAnimationFade];
[deleteDic removeAllObjects];
[array release];
}
//编辑按钮
-(void)editbtnClick
{
if ([self.navigationItem.rightBarButtonItem.title isEqual: @"编辑"])
{
self.navigationItem.rightBarButtonItem.title = @"确定";
[self.mytableView setEditing:YES animated:YES];
}
else
{
self.navigationItem.rightBarButtonItem.title = @"编辑";
[deleteDic removeAllObjects];
[self.mytableView setEditing:NO animated:YES];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.navigationItem.rightBarButtonItem.title isEqual: @"确定"])
{
[deleteDic setObject:indexPath forKey:[array objectAtIndex:indexPath.row]];
}
}