为什么我的函数被调用了两次?

时间:2011-07-08 09:44:08

标签: iphone objective-c ios uitableview

我在表格视图中附加了一个滑动识别器

- (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 个答案:

答案 0 :(得分:4)

在更改cellWasSwiped州时,您的UIGestureRecognizer可以被多次调用。您需要检查属性state,当用户完成其操作时,它将为UIGestureRecognizerStateEnded。检查状态UIGestureRecognizerStateFailedUIGestureRecognizerStateCancelled

也很不错

答案 1 :(得分:3)

我在表格单元格中滑动时遇到了同样的问题。我的识别器方法使用状态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];
}

答案 2 :(得分:1)

您可以将其添加到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];
        // ...
  }
}