【问题标题】:iOS: Why does hidden button still receive tap events?iOS:为什么隐藏按钮仍然接收点击事件?
【发布时间】:2016-10-21 09:07:43
【问题描述】:

根据 Apple 文档,隐藏的 UIButtons 不应接收点击事件。

但是,我们的应用程序有一个 UIButton 尽管被隐藏,但仍接收点击事件。

此函数是点击按钮时调用的IB Action。当按钮从 Storyboard 中移除时,不会调用此函数。当按钮被添加到 Storyboard 时,函数会被调用——即使按钮被隐藏了。

为了验证按钮是否隐藏,我们在函数中放置了一个断点,并从 Xcode 调试器运行 expr sender.hidden。结果:是的。

堆栈跟踪显示 IB 操作是由 UIApplicationMain 中的代码触发的,而不是我们的代码。

通过 Connections Inspector,我们确认除了神秘按钮之外,IB 操作没有其他触发器。

彻底糊涂了。有什么建议吗?

@IBAction func buttonTapped(sender: UIButton) {        
    // If here, handle tap
    ...
}

【问题讨论】:

  • 您是否以任何方式以编程方式触发按钮点击?
  • 按钮隐藏时可以设置userInteractionEnable = false
  • @Watson nope 没有以编程方式触发按钮。
  • 如果您的 IBAction 被另一个 UIObject 或按钮引用,您可以检查模拟器视图层次结构
  • @MuhammadAdnan userInteractionEnable 应该不需要。根据 Apple 文档,隐藏的 UIButtons 不应接收手势事件。

标签: ios swift uiview uibutton storyboard


【解决方案1】:

我遇到的一种情况是,我正在根据应用程序状态在两个不同的按钮之间切换。当我创建这两个按钮中的第二个时,我复制并粘贴了第一个。这也复制了第一个按钮的插座。

我以为只显示第二个按钮时按下了第一个按钮,但实际上第二个按钮正在向我想要的插座和我复制第一个按钮时设置的插座发送事件。

要确定您的情况是否属于这种情况,请转到界面构建器,选择您的按钮,并检查触摸事件是否在连接检查器中完全按照您的要求设置。如果任何连接错误,您可以通过单击小“x”来删除它们。

【讨论】:

    【解决方案2】:

    尝试像这样设置 enable = false:

    button.enabled = false
    

    对于 Swift 3 来说:

    button.isEnabled = false
    

    【讨论】:

      【解决方案3】:

      问题是 UIButton 扩展不完整,在确定命中测试时没有考虑可见性。

      此函数正确处理 UIButton 被隐藏的情况。

      extension UIButton {
          public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
              // Ignore if button hidden
              if self.hidden {
                  return nil
              }
      
              // If here, button visible so expand hit area
              let hitSize = CGFloat(56.0)
              let buttonSize = self.frame.size
              let widthToAdd = (hitSize - buttonSize.width > 0) ? hitSize - buttonSize.width : 0
              let heightToAdd = (hitSize - buttonSize.height > 0) ? hitSize - buttonSize.height : 0
              let largerFrame = CGRect(x: 0-(widthToAdd/2), y: 0-(heightToAdd/2), width: buttonSize.width+widthToAdd, height: buttonSize.height+heightToAdd)
              return (CGRectContainsPoint(largerFrame, point)) ? self : nil
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-12
        • 2012-06-13
        • 1970-01-01
        相关资源
        最近更新 更多