我将UISwipeGestureRecognizer附加到UITableViewCell方法中的cellForRowAtIndexPath:上,如下所示:

- (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];

        UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)];
        gesture.direction = UISwipeGestureRecognizerDirectionRight;
        [cell.contentView addGestureRecognizer:gesture];
        [gesture release];
    }
    return cell;
}

但是,成功刷卡后,didSwipe方法总是被调用两次。我最初以为这是因为手势开始和结束,但是如果我注销了gestureRecognizer本身,它们都处于“Ended”状态:
-(void)didSwipe:(UIGestureRecognizer *)gestureRecognizer {

    NSLog(@"did swipe called %@", gestureRecognizer);
}

安慰:
2011-01-05 12:57:43.478 App[20752:207] did swipe called <UISwipeGestureRecognizer: 0x5982fa0; state = Ended; view = <UITableViewCellContentView 0x5982c30>; target= <(action=didSwipe:, target=<RootViewController 0x5e3e080>)>; direction = right>
2011-01-05 12:57:43.480 App[20752:207] did swipe called <UISwipeGestureRecognizer: 0x5982fa0; state = Ended; view = <UITableViewCellContentView 0x5982c30>; target= <(action=didSwipe:, target=<RootViewController 0x5e3e080>)>; direction = right>

我真的不知道为什么。我显然尝试检查Ended状态,但这无济于事,因为它们都以“Ended”的形式出现...有什么想法吗?

最佳答案

您可以将其添加到viewDidLoad中的表 View 中,而不是直接将手势识别器添加到单元格中。

didSwipe -Method中,可以如下确定受影响的IndexPath和单元格:

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

  if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        CGPoint swipeLocation = [gestureRecognizer locationInView:self.tableView];
        NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
        UITableViewCell* swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
        // ...
  }
}

关于ios - UIGestureRecognizer和UITableViewCell问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4604296/

10-10 20:49