一:在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方法
1 - (void)delete 2 { 3 // 设置表格的编辑属性 4 [self.tableView setEditing:!self.tableView.editing animated:YES]; 5 } 6 #pragma mark - 重写表格的编辑状态的setter方法 7 - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 8 { 9 NSLog(@"%s!!!!!!!!",__func__); 10 if (indexPath.row == 0) { 11 // 当行号为0时,返回添加按钮状态 12 return UITableViewCellEditingStyleInsert; 13 } 14 // 当行号不为0时,返回删除按钮状态 15 return UITableViewCellEditingStyleDelete; 16 }
三:当用户点击编辑状态下的按钮时,实现删除联系人或者增加联系人
1 //点击 编辑状态表格的按钮 系统会调用的方法 2 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 3 { 4 // 判断用户点击的按钮类型 5 if (editingStyle == UITableViewCellEditingStyleDelete) { 6 // 在数组中删除该联系人 7 //1.先获取该联系人 8 NSInteger pathOfRow = indexPath.row; 9 [self.contacts removeObject:self.contacts[pathOfRow]]; 10 // 刷新表格 11 [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; 12 // 同步沙盒数据 13 [NSKeyedArchiver archiveRootObject:self.contacts toFile:self.contactPath]; 14 } 15 // 当用户点击增加按钮事件时 16 if (editingStyle == UITableViewCellEditingStyleInsert) { 17 contact *con = [[contact alloc] init]; 18 con.name = @"赵小姐"; 19 con.tel = @"10086"; 20 [self.contacts addObject:con]; 21 NSIndexPath *path = [NSIndexPath indexPathForItem:indexPath.row +1 inSection:0]; 22 [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationLeft]; 23 [NSKeyedArchiver archiveRootObject:self.contacts toFile:self.contactPath]; 24 } 25 }
四 实际效果: