简体   繁体   English

检测不在UISubView上的轻击手势

[英]Detecting tap gesture that is not on a UISubView

I have three UIButton instances: buttonA , buttonB and buttonC . 我有三个UIButton实例: buttonAbuttonBbuttonC Each button has its own center and occupies a certain size. 每个按钮都有自己的中心并占据一定的大小。

I want these buttons to "do something" (ie have the alpha values change) when the the screen is tapped anywhere except for where the buttons are, such that one can pressed the buttons to have their action s triggered without "doing this something" happening. 我希望这些按钮在屏幕上除按钮所在的位置以外的任何地方轻按时,即可“执行某项操作”(即,更改alpha值),以便人们可以按下按钮以触发其action而无需“进行此操作”发生。

What's the best way to go about this, please? 请问最好的方法是什么?

Try something like this: 尝试这样的事情:

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

Where b, b2, and b3 are each of your buttons. 其中b,b2和b3是每个按钮。

This works like any other tap. 就像其他任何水龙头一样工作。 Just give the "elsewhere" (eg the view controller's main view) a UITapGestureRecognizer and respond when the user taps it. 只需给“其他地方”(例如,视图控制器的主视图)提供一个UITapGestureRecognizer并在用户点击它时做出响应。 It won't be triggered when you tap one of the buttons, because in that case the button will eat the tap. 当您点击其中一个按钮时,它不会被触发,因为在这种情况下,该按钮会占用点击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM