【问题标题】:Why is the UITapGestureRecognizer never getting called with state began?为什么 UITapGestureRecognizer 永远不会在状态开始时被调用?
【发布时间】:2021-09-09 14:59:07
【问题描述】:

如果您将 UITapGestureRecognizer 分配给 UIView,则当用户触摸视图时,UIGestureRecognizerStateBegan 不会出现。

// Tap

_tapGestureRecognizer =
[[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tap:)];
    
[_someView addGestureRecognizer:_tapGestureRecognizer];

当用户执行点击时,识别器会直接跳转到 UIGestureRecognizerStateEnded

我必须将该视图更改为 UIButton 并监听 touchDown 方法。

_someButton = [[UIButton alloc] init];
    
[_someButton addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
    
[self addSubview: _someButton];

我不喜欢仅仅为此将 UIView 更改为 UIButton

我可以改用 UITapGestureRecognizer 吗?

【问题讨论】:

    标签: ios uiview uibutton uigesturerecognizer


    【解决方案1】:

    首先让我说UITapGestureRecognizer docs 清楚地告诉我们期待所有状态的回调。

    对于手势识别,指定数量的手指必须点击视图指定的次数。 虽然点击是离散的手势,但它们对于手势识别器的每个状态都是离散的。系统会在手势开始时发送相关的操作消息,然后针对每个中间状态再次发送,直到(包括)手势的结束状态。处理轻击手势的代码应测试手势的状态,例如:

    func handleTap(sender: UITapGestureRecognizer) {
        if sender.state == .ended {
            // handling code
        }
    }
    

    然而它几乎没有意义(特别是在单击识别器的情况下)。您触摸了一个视图(添加了轻击手势),您还没有抬起手指,移动它等。系统在.touchDown 事件发生时无法知道此交互将变成成功识别点击(需要抬起手指)。

    基本上UITapGestureRecognizer(对于单点触摸)是.touchDown + .touchUp 组合。如果在.touchDown 之后发生任何其他事情,例如拖动(.touchDragInside.touchDragExit),可能会导致成功识别平移手势(tableView 滚动等)

    您可以认为UITapGestureRecognizer 大致相当于 到按钮的.touchUpInside 事件。按钮的 .touchUpInside 事件不会为 .touchDown 事件调用您的函数,只能通过明确请求相同的方法来接收该事件。

    文档为什么这么说?

    也许系统能够为其他场景识别.began 状态

    1. 多次点击手势 - 双击/三次点击(请参阅UITapGestureReconizer.numberOfTapsRequired

    2. 多点触控 - 2/3 手指点击(请参阅 UITapGestureReconizer.numberOfTouchesRequired

    如果您想了解更多信息,您必须为此测试其他场景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      相关资源
      最近更新 更多