IOS-UITableView入门(3)

UITableView本身自带了(增、删)编辑功能:

1.仅仅要调用UITableView的编辑代码 就会进入编辑状态:

[self.tableView setEditing:!self.tableView.editing animated:YES];


2.进入编辑状态的UITableView会调用代理的

- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:以便推断是添加还是删除的方法。

UITableViewCellEditingStyle为一个枚举值,如UITableViewCellEditingStyleDelete,UITableViewCellEditingStyleInsert

总体的代码例如以下:

#pragma mark 点击编辑删除- (IBAction)trashClick:(id)sender { self.tableView.tag=EDIT_MOVE; [self.tableView setEditing:!self.tableView.editing animated:YES];}#pragma mark -TableViewDataSource#pragma mark 当出现编辑状态时 假设是删除状态时 点击删除保存时调用的方法#pragma mark 当为添加状态事 点击添加button保存时调用的方法- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if (tableView.tag==20) { [self.arr removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; } else { [self.arr insertObject:@"new row..." atIndex:indexPath.row+1]; NSIndexPath *indexNew=[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]; [tableView insertRowsAtIndexPaths:@[indexNew] withRowAnimation:UITableViewRowAnimationRight]; } }#pragma mark 点击编辑时出现的删除或者添加的button- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{ if (tableView.tag==20) { return UITableViewCellEditingStyleDelete; } else { return UITableViewCellEditingStyleInsert; }}#pragma mark 移动item时,以便编辑模式后还能保存编辑的顺序-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{ NSString *currStr=self.arr[sourceIndexPath.row]; [self.arr removeObjectAtIndex:sourceIndexPath.row]; [self.arr insertObject:currStr atIndex:destinationIndexPath.row]; [tableView reloadData];}#pragma mark 点击编辑添加- (IBAction)addClick:(id)sender { self.tableView.tag=EDIT_ADD; [self.tableView setEditing:!self.tableView.editing animated:YES];}


删除、移动的界面
添加item的界面

相关文章