手势识别器和TableView

Jim*_*m B 13 uitableview uigesturerecognizer

我有一个UIView,它涵盖了所有的UITableView.UIView正在使用手势识别器来控制表格显示的内容.我仍然需要垂直UITableView滚动和行点击.如何从手势识别器将这些传递到桌面?

jwh*_*hat 31

如果您需要知道您的单元格的indexPath:

- (void)handleSwipeFrom:(UIGestureRecognizer *)recognizer {
    CGPoint swipeLocation = [recognizer locationInView:self.tableView];
    NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
    UITableViewCell *swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
}
Run Code Online (Sandbox Code Playgroud)

之前在UIGestureRecognizer和UITableViewCell问题中已经回答过这个问题.


Rob*_*ner 30

将您的手势分配到表格视图,表格将处理它:

UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc]
        initWithTarget:self action:@selector(handleSwipeFrom:)];
[gesture setDirection:
        (UISwipeGestureRecognizerDirectionLeft
        |UISwipeGestureRecognizerDirectionRight)];
[tableView addGestureRecognizer:gesture];
[gesture release];
Run Code Online (Sandbox Code Playgroud)

然后在你的手势动作方法中,根据方向行动:

- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        [self moveLeftColumnButtonPressed:nil];
    }
    else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        [self moveRightColumnButtonPressed:nil];
    }
}
Run Code Online (Sandbox Code Playgroud)

该表格仅会在您内部处理后向您传递您要求的手势.

  • 这不起作用 - UISwipeGestureRecognizer上的direction属性指示可以识别哪些方向(在这种情况下左右),而不是WAS滑动的方向.您需要将手势识别器分开 (5认同)

小智 7

我尝试了Rob Bonner的建议并且效果很好.谢谢.

但是,就我而言,方向识别存在问题.(recognizer.direction总是引用3)我正在使用IOS5 SDK和Xcode 4.

它似乎是由"[gesture setDirection:(left | right)]"引起的.(因为预定义的(dir left | dir right)计算结果是3)

因此,如果某人遇到像我这样的问题,并且想要识别左右分别滑动,则将两个识别器指定给具有不同方向的表格视图.

像这样:

UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] 
                                             initWithTarget:self
                                             action:@selector(handleSwipeLeft:)];
[swipeLeftGesture setDirection: UISwipeGestureRecognizerDirectionLeft];

UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] 
                                              initWithTarget:self 
                                              action:@selector(handleSwipeRight:)];

[swipeRightGesture setDirection: UISwipeGestureRecognizerDirectionRight];

[tableView addGestureRecognizer:swipeLeftGesture];
[tableView addGestureRecognizer:swipeRightGesture];
Run Code Online (Sandbox Code Playgroud)

和手势动作如下:

- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)recognizer {
    [self moveLeftColumnButtonPressed:nil];
}

- (void)handleSwipeRight:(UISwipeGestureRecognizer *)recognizer {
    [self moveRightColumnButtonPressed:nil];
}
Run Code Online (Sandbox Code Playgroud)

我使用ARC功能编码,如果您不使用ARC,请添加版本代码.

PS:我的英语不太好,所以如果有任何句子错误,校正将非常高兴:)