UIGestureRecognizer和UITableViewCell问题

moo*_*ots 44 iphone uitableview ipad uigesturerecognizer ios

我在这样的方法中附加一个UISwipeGestureRecognizera :UITableViewCellcellForRowAtIndexPath:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

但是,该didSwipe方法在成功滑动时始终被调用两次.我最初认为这是因为手势开始和结束,但如果我注销gestureRecognizer本身,它们都处于"结束"状态:

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

    NSLog(@"did swipe called %@", gestureRecognizer);
}
Run Code Online (Sandbox Code Playgroud)

安慰:

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>
Run Code Online (Sandbox Code Playgroud)

我真的不知道为什么.我试着明确检查结束状态,但这没有任何帮助,因为它们都以"结束"的方式进入......任何想法?

Fel*_*lix 109

您可以将其添加到桌面视图中,而不是直接将手势识别器添加到单元格中viewDidLoad.

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];
        // ...
  }
}
Run Code Online (Sandbox Code Playgroud)