一:在viewDidLoad方法中代码添加一个UIBarButtonItem,并将其的类型设置成垃圾桶,代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = [NSString stringWithFormat:@"%@的联系人",self.name];
// 增加一个删除联系人的按钮
UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(delete)];
[self.navigationItem setRightBarButtonItems:@[deleteItem,self.navigationItem.rightBarButtonItem]];
}
二:实现delete方法,并重写表格编辑状态的setter方法
- (void)delete
{
// 设置表格的编辑属性
[self.tableView setEditing:!self.tableView.editing animated:YES];
}
#pragma mark - 重写表格的编辑状态的setter方法
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%s!!!!!!!!",__func__);
if (indexPath.row == ) {
// 当行号为0时,返回添加按钮状态
return UITableViewCellEditingStyleInsert;
}
// 当行号不为0时,返回删除按钮状态
return UITableViewCellEditingStyleDelete;
}
三:当用户点击编辑状态下的按钮时,实现删除联系人或者增加联系人
//点击 编辑状态表格的按钮 系统会调用的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// 判断用户点击的按钮类型
if (editingStyle == UITableViewCellEditingStyleDelete) {
// 在数组中删除该联系人
//1.先获取该联系人
NSInteger pathOfRow = indexPath.row;
[self.contacts removeObject:self.contacts[pathOfRow]];
// 刷新表格
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
// 同步沙盒数据
[NSKeyedArchiver archiveRootObject:self.contacts toFile:self.contactPath];
}
// 当用户点击增加按钮事件时
if (editingStyle == UITableViewCellEditingStyleInsert) {
contact *con = [[contact alloc] init];
con.name = @"赵小姐";
con.tel = @"";
[self.contacts addObject:con];
NSIndexPath *path = [NSIndexPath indexPathForItem:indexPath.row + inSection:];
[self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationLeft];
[NSKeyedArchiver archiveRootObject:self.contacts toFile:self.contactPath];
}
}
四 实际效果: