UITableView - удаление последней ячейки в разделе - PullRequest
1 голос
/ 28 января 2012

Это мой код для удаления ячейки в моем 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
    }
}

1 Ответ

4 голосов
/ 28 января 2012

Ваша проблема заключается в реализации вашего numberOfRowsInSection: метода. Ваше удаление, кажется, в порядке. Когда вы удалили строки, я думаю, что вы не можете обновить источник, используемый для возврата количества строк в методе numberOfRowsInSection:. Из-за несоответствия вы получаете ошибку. Пожалуйста, поделитесь этим кодом.

...