Анимированная анимация при удалении UITableViewCell - PullRequest
0 голосов
/ 02 ноября 2011

Я использую этот код для удаления UITableViewCell, но когда я удару пальцем, чтобы удалить, он сначала показывает знак минус справа, а затем удаление.

Я снял видео, чтобы проиллюстрировать свою точку зрения: Видео на YouTube

- (void)setEditing:(BOOL)editing animated:(BOOL)animate
{
    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.leftBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        PFObject *routine= [self.routineArray objectAtIndex:indexPath.row];
        [routine deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (!error) {
                [self.routineArray removeObjectAtIndex:indexPath.row];
                [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                //         [MKInfoPanel showPanelInView:self.view type:MKInfoPanelTypeError title:@"Routine Deleted" subtitle:@"You have succesfully deleted the routine!" hideAfter:2];
            } else {
                NSLog(@"%@", error);
            }
        }];   
    }
}

Edit:

- (void)loadData
{
    PFQuery *query = [PFQuery queryWithClassName:@"Routine"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.routineArray = [objects mutableCopy];
            [self.tableView reloadData];
        } else {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];   
}

-(void)addRoutine
{   
    PFObject *routine = [[PFObject alloc] initWithClassName:@"Routine"];
    [routine setObject:self.entered forKey:@"name"]; 
    [routine saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            [self loadData];
        } else {
            // There was an error saving the routine.
        }
    }];   
}

1 Ответ

2 голосов
/ 02 ноября 2011

Похоже, есть две проблемы.Сначала это выглядит как -deleteInBackgroundWithBlock: требуется значительное время для выполнения своего блока после нажатия кнопки удаления.Вы можете попробовать удалить объект dataSource и строку tableView перед удалением данных из основного хранилища данных, если вы не используете NSFetchedResultsController

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        PFObject *routine = [self.routineArray objectAtIndex:indexPath.row];
        [self.routineArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [routine deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (!error) {
                //[MKInfoPanel showPanelInView:self.view type:MKInfoPanelTypeError title:@"Routine Deleted" subtitle:@"You have succesfully deleted the routine!" hideAfter:2];
            } else {
                NSLog(@"%@", error);
            }
        }];   
    }
}

. Вы также можете использовать другую анимацию, если предпочитаете что-то другое.чем затемнение непрозрачности ряда.Если вы ориентируетесь только на iOS 5.0, вы можете использовать UITableViewRowAnimationAutomatic, чтобы UIKit пытался выбрать наиболее привлекательную анимацию с учетом обстоятельств.

Другая проблема выглядит так, как будто режим редактирования снова включается после нажатия кнопки удаления.Вам не нужно переопределять -setEditing:animated:, поэтому попробуйте полностью удалить этот метод.В вашем -viewDidLoad: вы можете сделать следующее, чтобы получить режим редактирования бесплатно:

self.navigationItem.leftBarButtonItem = self.editButtonItem;

См .:

Следует также отметить, что при проверке состояния редактирования следует использовать средство доступа isEditing.

Чтобы не вызывать -reloadData, вы просто добавляете один новый объект в свой массив dataSource, затем добавляете строку tableView, а затем сохраняете ее в основном хранилище данных.Это просто противоположность того, что вы должны были сделать при удалении строки из табличного представления.Это будет работать, если вам нужно добавить объект routine в конец tableView, и нет никакого пользовательского порядка сортировки.В противном случае вы должны вставить объект routine в self.routineArray по желаемому индексу и затем создать правильный indexPath для вставки строки tableView в нужное место в tableView.

- (void)addRoutine
{   
    PFObject *routine = [[PFObject alloc] initWithClassName:@"Routine"];
    [routine setObject:self.entered forKey:@"name"]; 
    [self.routineArray addObject:routine];
     NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([self.routineArray count]-1) inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath withRowAnimation:UITableViewRowAnimationAutomatic
    [routine saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            [self loadData];
        } else {
            // There was an error saving the routine.
        }
    }];   
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...