Как удалить строки из UITableView с анимацией?

У меня проблемы с удалением строк из табличного представления. Я использую приведенный ниже код при нажатии кнопки удаления в строке:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:control.tag-100 inSection:0];
[resultList removeObjectAtIndex:indexPath.row];
[resultView beginUpdates];
[resultView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[resultView endUpdates];
//[resultView reloadData];

Первая строка была успешно удалена, но затем индексы были неверными. Поэтому, когда я удаляю последнюю строку, это дает исключение index out of bounds.

Код генерации ячеек:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"personalizeTableCell";

    PersonalizeCell *cell = (PersonalizeCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[PersonalizeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];        
    cell.title.text = @"text";
    cell.rateView.tag = indexPath.row + 100;
    return cell;
}

Где я не прав?

ОБНОВИТЬ:

    for (NSInteger j = 0; j < [venuesTableView numberOfSections]; ++j)
    {
        for (NSInteger i = 0; i < [venuesTableView numberOfRowsInSection:j]; ++i)
        {
           PersonalizeCell* cell = (PersonalizeCell*)[venuesTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]];
           cell.rateView.tag = 100 + i;
        }
    }

решил мою проблему. Спасибо Ненаду М.


person Burak    schedule 07.02.2013    source источник


Ответы (1)


Предполагая, что ваш [NSIndexPath indexPathForRow:control.tag-100 inSection:0]; возвращает правильный путь индекса .... Вы пытались переместить вызов removeObjectAtIndex внутри "скобки" begin- / end-updates ?:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:control.tag-100 inSection:0];
[resultView beginUpdates];
[resultList removeObjectAtIndex:indexPath.row];
[resultView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[resultView endUpdates];

ОБНОВИТЬ:

Очевидно, ваш cell.rateView.tag стал неправильным после того, как вы удалили свою первую ячейку. Поэтому после каждого удаления (т.е. каждого removeObjectAtIndex...) вы должны повторно перебирать оставшиеся ячейки tableview и повторно назначать правильное значение тега (cell.rateView.tag = indexPath.row + 100)! В противном случае ваш [NSIndexPath indexPathForRow:control.tag-100 inSection:0]; вернет неправильный indexPath, что приведет к ошибке выхода за пределы!

Переназначение значений тегов:

Вам не нужно перезагружать всю таблицу, просто прокрутите оставшиеся ячейки и повторно назначьте значение тега после [resultView endUpdates];:

NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
    for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
    {
        [cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
    }
}

А теперь сделайте:

for (PersonalizeCell* cell in cells)
{
    cell.rateView.tag = // new calculated tag
}

(Или выполните переназначение даже во внутреннем цикле первого фрагмента кода напрямую.)


Вот действительно типичный код для всего процесса, в примере две строчки из таблицы:

Обратите внимание, что facebookRowsExpanded - это переменная класса, которую вы должны иметь:

if ( [theCommand isEqualToString:@"fbexpander"] )
{
NSLog(@"expander button......");
[tableView deselectRowAtIndexPath:indexPath animated:NO];

NSArray *deleteIndexPaths;
NSArray *insertIndexPaths;

facebookRowsExpanded = !facebookRowsExpanded;
// you must do that BEFORE, not AFTER the animation:

if ( !facebookRowsExpanded ) // ie, it was just true, is now false
    {
    deleteIndexPaths = [NSArray arrayWithObjects:
            [NSIndexPath indexPathForRow:2 inSection:0],
            [NSIndexPath indexPathForRow:3 inSection:0],
             nil];
    [tableView beginUpdates];
    [tableView
        deleteRowsAtIndexPaths:deleteIndexPaths
        withRowAnimation: UITableViewRowAnimationMiddle];
    [tableView endUpdates];
    }
else
    {
    insertIndexPaths = [NSArray arrayWithObjects:
            [NSIndexPath indexPathForRow:2 inSection:0],
            [NSIndexPath indexPathForRow:3 inSection:0],
             nil];
    [tableView beginUpdates];
    [tableView
        insertRowsAtIndexPaths:insertIndexPaths
        withRowAnimation: UITableViewRowAnimationMiddle];
    [tableView endUpdates];
    }

// DO NOT do this at the end: [_superTableView reloadData];
return;
}

ПРИМЕЧАНИЕ: ваш код для numberOfRowsInSection должен использовать facebookRowsExpanded.

(это будет что-то вроде «если facebookRowsExpanded вернет 7, иначе вернет 5»)

ПРИМЕЧАНИЕ: ваш код для cellForRowAtIndexPath должен использовать facebookRowsExpanded.

(он должен возвращать правильную строку, в зависимости от того, развернуты вы или нет.)

person Nenad M    schedule 07.02.2013
comment
Все нормально работало до последнего ряда. Когда дело доходит до последнего ряда, он снова застревает. Думаю, после удаления строки тег не переназначается - person Burak; 07.02.2013
comment
Да, поэтому мне следует перезагрузить таблицу. Если перезагружаю, анимации не происходит - person Burak; 07.02.2013