iOS按钮可见,不可点击

时间:2017-07-29 17:12:18

标签: ios uibutton uistoryboard

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

由于某些原因,按钮根本无法点击。因此,当您点击它时,按钮会在您松开之前或按住按钮时略微改变颜色。但是这种行为由于某种原因并没有发生,并且连接到按钮的功能根本就没有被调用。

这似乎是某些内容重叠或位于按钮顶部的问题。该按钮完全可见并启用,但所有内容均无法点击。我尝试了Debug View Hierarchy,但在该视图中一切看起来都是正确的。

为什么会发生这种情况的任何想法?

编辑我尝试使用以下代码创建一个类,并在界面构建器中将容器视图设置为该类。

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
    }
}

1 个答案:

答案 0 :(得分:2)

使用hitTest(_:with:) method。当我们调用super.hitTest(point, with: event)时,超级调用返回nil,因为禁用了用户交互。因此,我们检查touchPoint是否在UIButton上,如果是,则我们可以返回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) {

    }
}