Удаление ячейки из таблицы - Код предоставлен - PullRequest
0 голосов
/ 14 февраля 2012

У меня есть tableviewController.На UINavigationBar я добавлю кнопку под названием Edit.Когда пользователь нажимает на него, мне нужно, чтобы все ячейки перешли в режим редактирования, где они могли бы удалять записи.

Я полагаю, что следующий метод делает это.Я прав ?получу ли я красный круг и кнопку удаления в ячейке, когда нажму кнопку редактирования?

2.) Как мне написать код для кнопки редактирования (UIBarbuttonitem), когда пользователь щелкает еевызвать следующий метод?

3.) Когда мы удаляем ячейку, мне нужно перезагрузить данные в таблице.Я написал код для этого, это правильно.(Я не в моем Mac в данный момент)

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        [self.tableView beginUpdates];
        [discardedItems addObject:[self.entries objectAtIndex:indexPath.row]];
        [self.itemsMutableArray removeObjectsInArray:discardedItems ]; 
        self.entries = [NSArray arrayWithArray:self.itemsMutableArray];
        [self.tableView endUpdates];

        [self.tableView reloadData];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

Ответы [ 2 ]

1 голос
/ 14 февраля 2012

Ваш код не выглядит неправильно. Но так много строк для такой маленькой работы. Вы также убиваете анимацию с помощью reloadData. И вы оборачиваете вызовы, которые даже не касаются tableView в beginUpdates / endUpdates.

Почему бы не использовать NSMutableArray в качестве источника данных? Вы можете уменьшить число строк кода до двух:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // delete the item from the datasource
        [self.entries removeObjectAtIndex:indexPath.row];
        // Delete the row from the table view
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
1 голос
/ 14 февраля 2012

Прежде всего, вам нужно указать, можно ли редактировать строки. Это делается следующим способом

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

верните yes, если вы хотите, чтобы все строки были редактируемыми.

Чтобы получить красные круги, используйте,

Возможно, в методе, вызываемом кнопкой редактирования ...

UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Edit ", @"") style:UIBarButtonItemStyleBordered target:self action:@selector(pressedEdit:)];
self.navigationItem.leftBarButtonItem = editButton;

(в viewdidload)

и в нажатом редакторе:

- (void) pressedEdit :(id)sender {
    UIBarButtonItem *editButton = (UIBarButtonItem*)self.navigationItem.leftBarButtonItem;

    if (!self.tabeView.editing) {
        [self.tableView setEditing:YES animated:YES];
        editButton.title = NSLocalizedString(@"Done", @"");
    }
    else {
        [self.tableView setEditing:NO animated:YES];
        editButton.title = NSLocalizedString(@"Edit", @"");
    }
}

В соответствии с написанным вами кодом, я думаю, вам следует сначала обновить источник данных, а затем удалить ячейку ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...