Проведите пальцем влево или вправо в любом месте UITableViewCell, чтобы удалить ячейку без кнопки удаления? - PullRequest
8 голосов
/ 30 января 2012

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

Ответы [ 4 ]

6 голосов
/ 30 января 2012

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

  1. Ссылка на tableView, в котором он используется.
  2. IndexPath для поиска ячейки в tableView. (Обратите внимание, это необходимо обновлять каждый раз, когда вы удаляете ячейку для всех ячеек, где это изменяется)

В вашей cellForRowAtIndexPath:, где вы создаете пользовательскую ячейку, установите эти свойства. Также добавьте UISwipeGestureRecognizer в ячейку

cell.tableView=tableView;
cell.indexPath=indexPath;
UISwipeGestureRecognizer *swipeGestureRecognizer=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(deleteCell:)];
[cell addGestureRecognizer:swipeGestureRecognizer];
[swipeGestureRecognizer release];

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

-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if([[gestureRecognizer view] isKindOfClass:[UITableViewCell class]]&&
       ((UISwipeGestureRecognizer*)gestureRecognizer.direction==UISwipeGestureRecognizerDirectionLeft
        ||(UISwipeGestureRecognizer*)gestureRecognizer.direction==UISwipeGestureRecognizerDirectionRight)) return YES;
}

В вашем deleteCell:

-(void) deleteCell:(UIGestureRecognizer*)gestureRec
{
    UIGestureRecognizer *swipeGestureRecognizer=(UISwipeGestureRecognizer*)gestureRec;
    CustomCell *cell=[swipeGestureRecognizer view];
    UITableView *tableView=cell.tableView;
    NSIndexPath *indexPath=cell.indexPath;
    //you can now use these two to perform delete operation
}
3 голосов
/ 20 августа 2013

Решение, опубликованное @MadhavanRP, работает, но оно сложнее, чем нужно.Вы можете воспользоваться более простым подходом и создать один распознаватель жестов, который обрабатывает все пролистывания, которые происходят в таблице, а затем получить местоположение пролистывания, чтобы определить, какая ячейка была пролистана пользователем.

Чтобы настроить распознаватель жестов:

- (void)setUpLeftSwipe {
    UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                       action:@selector(swipeLeft:)];
    [recognizer setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.tableView addGestureRecognizer:recognizer];
    recognizer.delegate = self;
}

Вызовите этот метод в viewDidLoad

Для обработки пролистывания:

- (void)swipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer {
    CGPoint location = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
    ... do something with cell now that i have the indexpath, maybe save the world? ...
}

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

0 голосов
/ 30 января 2012

реализуйте

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

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;

эти два метода, если UITableViewCellEditingStyle равен UITableViewCellEditingStyleDelete, затем выполните sth, чтобы стереть вашу ячейку с помощью

- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;

, и все.

0 голосов
/ 30 января 2012

для этого вам нужно добавить этот код в ваш проект.

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
    }    
}

В противном случае вы можете перейти по этой ссылке ввести описание ссылки здесь

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