【问题标题】:Touch on button is not detected when a TapGestureRecognizer is attached to the container view将 TapGestureRecognizer 附加到容器视图时未检测到触摸按钮
【发布时间】:2019-03-07 07:29:12
【问题描述】:

在我的应用中,我有一个视图控制器,该视图具有附加的 tapGesture 识别器。

tapGesture 为一个隐藏的视图(某种面板)设置了动画,该视图变得可见。该视图包含一个按钮,该按钮可以执行某些操作,然后隐藏面板。

但似乎因为点击手势被附加到视图控制器的视图,没有检测到按钮上的触摸,只触发了视图控制器视图上的点击。

我尝试过使用 firstResponder,但似乎不起作用

func addGesture(){
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(togglePanel))
    myView.addGestureRecognizer(tapGesture)
}

我的面板是这样插入的:

 insertSubview(actionPanel, at: 0)

我的按钮

actionPanel.addSubview(dismissBtn)

按钮动作

dismissBtn.addTarget(self, action: #selector(hideActionPanel), for: .touchUpInside)

@objc func hideActionPanel(){
        print("tapped")
    }

【问题讨论】:

  • 您能帮我们将代码添加到您的问题中吗?
  • @azinwi 我更新了我的问题
  • 你实际运行addGesture()是什么时候?
  • 在我的视图模型的 init 中
  • @user1445685 您是否在任何视图中禁用任何用户交互?

标签: swift uiview uitapgesturerecognizer


【解决方案1】:

您可以将UIGestureRecognizerDelegate 添加到您的班级。要了解更多信息,请访问UIGestureRecognizerDelegate

然后实现func gestureRecognizer(UIGestureRecognizer, shouldReceive: UITouch) -> Bool。每次手势即将发生时都会调用此函数。如果您想确切了解它是如何工作的,请前往gestureRecognizer

不要忘记像这样将您的手势连接到代理。

tapGesture.delegate = self

最后,在 UIGestureRecognizerDelegate 函数中检查被触摸的视图是否等于具有手势识别器的视图。这将阻止任何底层视图识别手势。

if touch.view == gestureRecognizer.view { return true } return false

【讨论】:

    【解决方案2】:

    这个按钮似乎不起作用

    使用 xcode 运行应用,使用 Xcode "Debug View Hierarchy"

    这个按钮或者它的超级视图可能是.userInteractionEnabled = false

    我假设你的动画图像是一个超级视图,并且图像默认关闭用户交互

    添加这个xxImage.userInteractionEnabled = true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多