根据Apple文档,隐藏的UIButtons
不应接收点击事件。
但是,我们的应用有UIButton
次接收点击事件,尽管被隐藏了。
此功能是点击按钮时调用的IB Action
。从故事板中删除该按钮时,不会调用此功能。当按钮添加到Storyboard时,即使按钮被隐藏,也会调用该函数。
要验证按钮是否隐藏,我们在函数内部放置一个断点并从Xcode调试器运行expr sender.hidden
。结果:是的。
堆栈跟踪显示IB操作由UIApplicationMain中的代码触发,而不是我们的代码。
通过Connections Inspector,我们确认除了神秘的按钮之外没有其他IB动作触发器。
彻底迷茫。建议?
@IBAction func buttonTapped(sender: UIButton) {
// If here, handle tap
...
}
答案 0 :(得分:2)
尝试设置enable = false,如下所示:
button.enabled = false
对于Swift 3将是:
button.isEnabled = false
答案 1 :(得分:1)
问题是不完整的UIButton扩展,在确定命中测试时未考虑可见性。
此功能正确处理隐藏UIButtons的情况。
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
}
}
答案 2 :(得分:0)
我遇到的一种情况是,我正在根据应用程序状态在两个不同的按钮之间切换。创建这两个按钮中的第二个时,我复制并粘贴了第一个。这也复制了第一个按钮的插座。
我以为只有第二个按钮在显示时才按下第一个按钮,但实际上第二个按钮正在向我打算的插座和复制第一个按钮时设置的插座发送事件。
>要确定您是否遇到这种情况,请转到界面构建器,选择按钮,然后检查是否在连接检查器中精确设置了所需的触摸事件。如果任何连接有误,则可以通过单击小“ x”将其删除。