检测不在 UISubView 上的点击手势

Detecting tap gesture that is not on a UISubView

我有三个 UIButton 实例:buttonAbuttonBbuttonC。每个按钮都有自己的中心并占据一定的大小。

我希望这些按钮在点击屏幕时 "do something"(即更改 alpha 值)任何地方 除了按钮所在的位置, 这样一来就可以按下按钮来触发 actions 而不会 "doing this something" 发生。

请问最好的解决方法是什么?

尝试这样的事情:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // Get location of touch
    let pos = touches.first?.location(in: self.view)

    if !b.frame.contains(pos) && !b2.frame.contains(pos) && !b3.frame.contains(pos) {
        // Change alpha or do something else
    }
}

其中 b、b2 和 b3 分别是您的按钮。

这与其他水龙头一样。只需给 "elsewhere" (例如视图控制器的主视图)一个 UITapGestureRecognizer 并在用户点击它时响应。当你点击其中一个按钮时它不会被触发,因为在那种情况下按钮会吃掉点击。