2012-01-28 79 views
1

這是我的代碼在我的UITableView刪除單元格:UITableView-刪除最後一個單元部分

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    [tableView beginUpdates]; 

    if([tableView numberOfRowsInSection:[indexPath section]] > 1) { 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
      withRowAnimation:UITableViewRowAnimationFade]; 
    } else { 
     [tableView deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]] 
      withRowAnimation:UITableViewRowAnimationFade]; 
    } 

    [tableView endUpdates]; 
} 

還有被刪除單元格之前被更新了一些數據,但我寧願相信這是正確更新,因爲數據源數組的count每次刪除一個單元時總是少一個。這是預期的行爲。然而,出於某種原因,每當我刪除最後一個單元格中的一部分,我得到'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

這是非常令人沮喪,尤其是從什麼,因爲我已經能夠在網上找到,我正確地做這個。也許我需要睡眠,這是一段時間。這裏的任何想法?

解決方案:

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section { 
    if(tableIsEmpty) { 
     //**this** line was the culprit- returning zero here fixed the problem 
     return 0; 
    } else if(section == ([tableView numberOfSections] - 1)) { 
     //this is the last section- it only needs one row for the 'Delete all' button 
     return 1; 
    } else { 
     //figure out how many rows are needed for the section 
    } 
} 

回答

4

你的問題就出在你numberOfRowsInSection:方法的實現。您的刪除似乎很好。當您刪除行時,我認爲您無法更新用於返回numberOfRowsInSection:方法中的行數的源。由於那裏的不一致,你會得到錯誤。請分享該代碼。

+0

是的,是的!你完全正確。我想我需要的只是有人告訴我,我的問題*不是我的刪除代碼。我弄明白了 - 這與我總是用「全部刪除」單元顯示一個額外部分有關,而當最後一部分被刪除時,我沒有讓它消失。總之,你幫了很多忙,所以謝謝你! – 2012-01-28 06:26:42

+0

@Rickay很高興爲您提供幫助。 – MadhavanRP 2012-01-28 07:08:08

相關問題