實作方法如下:
1. 在viewDidLoad地方加入editButtonItem:
1 2 | // add native edit button on navigation bar
self.navigationItem.rightBarButtonItem = self.editButtonItem;
|
2. 在 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 應該加上:
1 2 3 4 | // If we're in editing mode, we add a placeholder row for creating new items. if (self.editing) { count++; } |
3. 在顯示table cell的部份,
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath 也要在每次table有變動時做更新:
1 2 3 4 5 6 7 | if (indexPath.row == [myArray count]) { // assign the content of last cell in editing mode [cell.textLabel setText:@"Add new data"]; cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator; } else { // assign other cell data } |
4. 當點選add new data的cell,
1 2 3 4 5 | if (indexPath.row == [myArray count]) { [myTable deselectRowAtIndexPath:indexPath animated:YES]; if (self.editing) { // Called after selection. In editing mode, this will navigate to a new view controller. } |
5. 回頭來看看當tableview的edit mode切換時要實作的部分,先加上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | - (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; [myTable setEditing:editing animated:animated]; [self.navigationItem setHidesBackButton:editing animated:YES]; [myTable beginUpdates]; NSUInteger wc = [myArray count]; NSArray *myInsertIndexPath = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:wc inSection:0]]; if (editing) { [myTable insertRowsAtIndexPaths:myInsertIndexPath withRowAnimation:UITableViewRowAnimationTop]; } else { [myTable deleteRowsAtIndexPaths:myInsertIndexPath withRowAnimation:UITableViewRowAnimationTop]; } [myTable endUpdates]; } |
6. 接下來是設定edit模式下cell 左邊的加減符號
1 2 3 4 5 6 7 8 | - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { // The editing style for a row is the kind of button displayed to the left of the cell when in editing mode. if (indexPath.row == [myArray count]) { return UITableViewCellEditingStyleInsert; } else { return UITableViewCellEditingStyleDelete; } } |
7. 有新增刪除就一定要update table的內容
1 2 3 4 5 6 | - (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Remove the corresponding object and delete the appropriate table view cell. [myArray removeObjectAtIndex:indexPath.row]; [myTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop]; } |
8. 這裡的例子是在別的頁面新增輸入要新增的cell內容,
所以需要一個完成後的實作function :
1 2 3 4 5 6 7 8 9 | - (void)addCellDone { // update array NSString *v =[NSString stringWithFormat:@"123"]; [self.weightArray addObject:v]; // reload table [myTable reloadData]; //remove modal view [self dismissModalViewControllerAnimated:YES]; } |
OK~你得到它了!