2012-01-02 51 views
0

在我的UITableView中,我在底部有一個插入控件的專用單元格,以允許用戶插入新行。UITableView - 當上面有一定數量的單元格時,刪除最後一個單元格

UITableView

我想要做什麼是刪除/隱藏該細胞時,有細胞的(在這種情況下8)一定數目的在其上方。

這是我到目前爲止有:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if (section == 1) { 
     if ([sites count] == [[BrowserController sharedBrowserController] maximumTabs]) { 
      return [sites count]; 
     } else { 
      return [sites count] + 1; 
     } 
    } else { 
     return 1; 
    } 
} 

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     ... 
    } else if (editingStyle == UITableViewCellEditingStyleInsert) { 
     NSString *newSiteAddress = [NSString stringWithString:@"http://"]; 

     [sites addObject:newSiteAddress]; 

     if ([sites count] == [[%c(BrowserController) sharedBrowserController] maximumTabs]) { 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     } 

     [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES]; 
     [[(BookmarkTextEntryTableViewCell *)[tableView cellForRowAtIndexPath:indexPath] textField] becomeFirstResponder]; 
    } 
} 

這將導致以下異常被拋出:

2/01/12 4:28:07.956 PM MobileSafari: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1. The number of rows contained in an existing section after the update (8) must be equal to the number of rows contained in that section before the update (8), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' 
*** First throw call stack: 
(0x2bc0052 0x2d51d0a 0x2b68a78 0x1cf2db 0x747518 0x75282a 0x7528a5 0x812481c 0x75e7bb 0x8b2d30 0x2bc1ec9 0x6c65c2 0x6c655a 0x76bb76 0x76c03f 0x76b2fe 0x984a2a 0x2b949ce 0x2b2b670 0x2af74f6 0x2af6db4 0x2af6ccb 0x491879 0x49193e 0x6c3a9b 0x4430 0x2db5) 

回答

0

下面是從Apple's UITableView documentation相關段落,其具有插入和刪除單元格的事情:

單擊插入或刪除控件會導致數據源 接收tableView:commitEditingStyle:forRowAtIndexPath:消息。 您可以通過調用 deleteRowsAtIndexPaths:withRowAnimation:或 insertRowsAtIndexPaths:withRowAnimation:來執行刪除或插入操作,如果適用。也在 編輯模式下,如果表視圖單元格的showsReorderControl 屬性設置爲YES,則數據源會收到一個 tableView:moveRowAtIndexPath:toIndexPath:message。數據源可以通過 tableView:canMoveRowAtIndexPath:選擇性地刪除單元格的重新排序控件。

你應該創建一個名爲「insertLastCell」和「deleteLastCell」新方法(或類似的規定),其中明確告訴你的表視圖中插入並通過insertRowsAtIndexPaths:withRowAnimation:deleteRowsAtIndexPaths:withRowAnimation:刪除最後一個單元格。

一旦插入和刪除「提交」,只有然後可以在numberOfRowsInSection方法中報告不同的數字。

相關問題