почему моя функция вызывается дважды? - PullRequest
3 голосов
/ 08 июля 2011

У меня в ячейке таблицы есть распознаватель пролистывания

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

      //swipe recognition
        UISwipeGestureRecognizer *g = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(cellWasSwiped:)];
        [cell addGestureRecognizer:g];
        [g release];


    }


    // Configure the cell...
    [[cell textLabel] setText:[NSString stringWithFormat:@" number %d", indexPath.row]];
    return cell;
}

и функция смахивания

- (void)cellWasSwiped:(UIGestureRecognizer *)g {
    NSLog(@"sunt in cellWasSwiped");
    swipeViewController *svc = [[swipeViewController alloc]init];
  [self.navigationController pushViewController:svc animated:YES];
  [svc release];
}

и, введя точки останова, я вижу, что моя функция считывания вызывается 2 раза, и на моем контроллере навигации установлены два идентичных контроллера вида. Почему моя функция смахивания вызывается дважды, когда я смахиваю ячейку?

Ответы [ 3 ]

4 голосов
/ 08 июля 2011

Ваш cellWasSwiped может быть вызван несколько раз при изменении состояния UIGestureRecognizer. Вам нужно проверить свойство state, это будет UIGestureRecognizerStateEnded, когда пользователь завершит свое действие. Также полезно проверить состояния UIGestureRecognizerStateFailed и UIGestureRecognizerStateCancelled.

3 голосов
/ 20 августа 2011

У меня была та же конкретная проблема со смахиванием в ячейке таблицы. Мой метод распознавания был вызван дважды с состоянием UIGestureRecognizerStateEnded.

Я работал над этим следующим образом:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  static NSString *CellIdentifier = @"CellIdentifier";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    //... create cell
    //... create swipe recognizer (in my case attached to cell's contentView)
  }

  for (UIGestureRecognizer* g in cell.contentView.gestureRecognizers)
    g.enabled = YES;
}

, а затем

-(void) cellWasSwiped: (UIGestureRecognizer*) recognizer {

  if (recognizer.state != UIGestureRecognizerStateEnded)
    return;

  if (recognizer.enabled == NO)
    return;

  recognizer.enabled = NO;

  //... handle the swipe
  //... update whatever model classes used for keeping track of the cells
  // Let the table refresh
  [theTable reloadData];
}
1 голос
/ 08 июля 2011

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

В методе cellWasSwiped вы можете определить затронутый IndexPath и ячейку следующим образом:

-(void)cellWasSwiped:(UIGestureRecognizer *)gestureRecognizer {

  if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        CGPoint swipeLocation = [gestureRecognizer locationInView:self.tableView];
        NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
        UITableViewCell* swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
        // ...
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...