- (void)viewDidLoad {
[super viewDidLoad];
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
tableView.tag = 1001;
tableView.delegate = self;
tableView.dataSource = self;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
[self.view addSubview:tableView];
[tableView release];
_dataSoure = [[NSMutableArray alloc] initWithObjects:@"a", @"b", @"c", @"d", nil];
// 系统自带编辑按钮 - 可以直接赋值使用
self.navigationItem.leftBarButtonItem = self.editButtonItem;
}
//系统自带编辑按钮的点击事件
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
UITableView *tableView = (UITableView *)[self.view viewWithTag:1001];
// 让tableView处于可编辑状态
[tableView setEditing:editing animated:animated];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataSoure.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
if (_dataSoure.count > indexPath.row) {
cell.textLabel.text = _dataSoure[indexPath.row];
}
return cell;
}
#pragma mark -- UITableViewEdit
//编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
// 分为none\添加\删除
// 当为第一个cell的时候可编辑属性为添加
if (indexPath.row == 0) {
return UITableViewCellEditingStyleInsert;
}
return UITableViewCellEditingStyleDelete;
}
//控制是否允许编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
//允许编辑
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
// 当样式为添加时
if (editingStyle == UITableViewCellEditingStyleInsert) {
[self.dataSoure addObject:@"��"];
[tableView reloadData];
}
// 删除
if (editingStyle == UITableViewCellEditingStyleDelete) {
// 先处理数据
[self.dataSoure removeObjectAtIndex:indexPath.row];
// 再刷新tableView
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}
//控制每一行是否可以移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
//移动完成执行的协议方法
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
NSString *string = self.dataSoure[sourceIndexPath.row];
[self.dataSoure removeObjectAtIndex:sourceIndexPath.row];
[self.dataSoure insertObject:string atIndex:destinationIndexPath.row];
[tableView reloadData];
}