iOS 按钮可见,不可点击

iOS Button Visible, Not Clickable

我的故事板中有一个视图,默认情况下 alpha 设置为 0。在某些情况下,Swift 文件将 alpha 设置为 1。所以要么隐藏,要么不隐藏。在此视图之前只包含 2 个标签。我正在尝试向视图添加 2 个按钮。

由于某些原因,这些按钮根本无法点击。因此,当您正常点击它时,按钮会在您释放之前或按住按钮时稍微改变颜色。但是由于某种原因并没有发生这种行为,并且根本没有调用连接到按钮的函数。

这似乎是一个重叠或按钮顶部的问题。该按钮是完全可见和启用的,除了不可点击之外的所有内容。我尝试了 Debug View Hierarchy 但在该视图中一切看起来都是正确的。

知道为什么会这样吗?

EDIT 我尝试使用以下代码制作 class,并在界面生成器中将容器视图设置为 class.

class AnotherView: UIView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        for view in self.subviews {
            if view.isUserInteractionEnabled, view.point(inside: self.convert(point, to: view), with: event) {
                return true
            }
        }

        return false
    }
}

选择 hitTest(_:with:) method。当我们调用 super.hitTest(point, with: event) 时,超级调用 returns nil,因为用户交互被禁用。因此,相反,我们检查触摸点是否在 UIButton 上,如果是,那么我们可以 return UIButton 对象。这会将消息发送到 UIButton 对象的选择器。

class AnotherView: UIView {

    @IBOutlet weak var button:UIButton!

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let view = super.hitTest(point, with: event)
        if self.button.frame.contains(point) {
            return button
        }
        return view
    }

    @IBAction func buttnTapped(sender:UIButton) {

    }
}