8

我使用以下代码将 UIPanGuestureRecognizer 添加到整个视图中:

UIPanGestureRecognizer *pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[[self view] addGestureRecognizer:pgr];

在主视图中,我有一个 UITableView,其中包含启用滑动删除功能的代码:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"RUNNING2");
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= _firstEditableCell && _firstEditableCell != -1)
        NSLog(@"RUNNING1");
        return YES;
    else
        return NO;
}

只有RUNNING1打印到日志中,删除按钮不显示。我相信这是因为 UIPanGestureRecognizer,但我不确定。如果这是正确的,我应该如何解决这个问题。如果这不正确,请提供原因并修复。谢谢。

4

3 回答 3

16

文件

如果手势识别器识别出它的手势,则视图的剩余触摸将被取消。

UIPanGestureRecognizer首先识别滑动手势,因此您UITableView不再接收触摸。

要使表格视图与手势识别器同时接收触摸,请将其添加到手势识别器的委托中:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
于 2013-08-22T08:51:03.580 回答
2

例如,如果您使用 UIPanGuestureRecognizer 来显示侧边菜单,那么当您在所有情况下都按照接受的答案中的建议返回 YES 时,您可能会看到一些不需要的副作用。例如,当您向上/向下滚动表格视图时打开侧边菜单(带有很少的左/右方向),或者当您打开侧边菜单时删除按钮行为异常。为了防止这种副作用,您可能想要做的是只允许同时进行水平手势。这将使删除按钮正常工作,但同时当您滑动菜单时其他不需要的手势将被阻止。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
    {
        UIPanGestureRecognizer *panGesture = (UIPanGestureRecognizer *)otherGestureRecognizer;
        CGPoint velocity = [panGesture velocityInView:panGesture.view];
        if (ABS(velocity.x) > ABS(velocity.y))
            return YES;
    }
    return NO;
}

或在斯威夫特:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    guard let panRecognizer = otherGestureRecognizer as? UIPanGestureRecognizer else {
        return false
    }
    let velocity = panRecognizer.velocity(in: panRecognizer.view)
    if (abs(velocity.x) > abs(velocity.y)) {
        return true
    }
    return false
}
于 2017-07-29T07:40:02.493 回答
0

如果接受的答案不起作用。尝试添加

panGestureRecognizer.cancelsTouchesInView = false

确保您没有直接将手势添加到 tableview。我在 ViewController 视图上添加了一个平移手势,并且可以确认它有效。

于 2019-05-01T02:05:01.873 回答