准备工作忽略
- 1.直接打开tab的可编辑模式 (默认样式为删除)
self.navigationItem.rightBarButtonItem = self.editButtonItem;
- 2.添加右上角编辑按钮
// 1.添加按钮
self.navigationItem.rightBarButtonItem = self.editButtonItem;
// 2.重写系统的编辑按钮点击触发的方法
- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
[self.tableView setEditing:editing animated:YES];
}
// 3.设置哪些行可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:
(NSIndexPath *)indexPath{
奇数行可以编辑, 偶数行不可以编辑
if (indexPath.row % 2 == 0) {
return NO;
}else{
return YES;
} 默认是yes
}
// 4.设置两种样式, 一个是插入, 一个是删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleDelete; // 删除
return UITableViewCellEditingStyleInsert; // 插入
}
// 5.修改按钮的标题 (提供左滑动的效果)
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:
(NSIndexPath *)indexPath{
return @"点我";
}
// 6.删除数据方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:
(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// 先删除数据源
[self.arr removeObjectAtIndex:indexPath.row];
// 方法1.直接刷新
//[self.tableView reloadData];
// 方法2. 通过tabl来删除上面的cell
// 第一个参数: 指定删除哪一个分区的哪一行, 把他作为一个元素放在数组中
// 第二个参数: 删除动画
[self.tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationBottom];
}
}
// 6.这个方法是iOS8.0之后出现的方法, 可以在编辑状态的时候有多少个按钮
- (NSArray *)tableView:(UITableView *)tableView
editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
// 第一个按钮
UITableViewRowAction *deleteAction = [UITableViewRowAction
rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除"
handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
// 按钮的点击所要触发的事件, 都是写在block中
NSLog(@"触发了删除按钮");
}];
// 第二个按钮
UITableViewRowAction *addAction = [UITableViewRowAction
rowActionWithStyle:UITableViewRowActionStyleDefault title:@"添加"
handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
// 按钮的点击所要触发的事件, 都是写在block中
NSLog(@"触发了添加按钮");
}];
deleteAction.backgroundColor = [UIColor blackColor];
addAction.backgroundColor = [UIColor purpleColor];
return @[deleteAction, addAction];
}
// 7.移动
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:
(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath
*)destinationIndexPath{
// 1.先获取到起始位置的数据
NSString *str = [self.arr[sourceIndexPath.row] retain];
// 2.把起始位置的对象从数据源中移除
[self.arr removeObjectAtIndex:sourceIndexPath.row];
// 3.把数据插入到数组的目的地的位置上区
[self.arr insertObject:str atIndex:destinationIndexPath.row];
[str release];
}