0

What's the best way to determine whether there is any active touch happening in a view hierarchy? Something like:

view.hasTouches

returns true if view or any of its descendant has active touches.

To those who would suggest using UIResponder's touch event handling API like touchesBegan, notice that view doesn't receive these calls if one of its descendant is handling the touch events.

an0
  • 17,191
  • 12
  • 86
  • 136
  • Do you have a specific use case? The `UIViewController` should call the `touchesBegan` for all its subviews. – Rikh May 26 '20 at 01:05
  • @Rikh Add a `UIButton` to your view. Tap the button. See whether your `UIViewController. touchesBegan` is called. – an0 May 26 '20 at 01:10
  • Ah so you specifically want to understand for `UIButton`. Probably because it has a parent as `UIControl` which eats up the touch it behaves a bit differently. Have a look at this https://stackoverflow.com/questions/631427/is-there-a-way-to-pass-touches-through-on-the-iphone . It is in Objective-C but the logic still holds. – Rikh May 26 '20 at 01:16
  • @Rikh I don't want to catch all touch events in all descendants and pass them up. For one it is too tedious. Secondly I may not have control of all the descendants anyway. I need a top-down approach. – an0 May 26 '20 at 01:23
  • Ah well, I unfortunately can't think of any possible solution that may help out in a top-down approach. – Rikh May 26 '20 at 01:31
  • @Rikh me either, that's why I ask here:) – an0 May 26 '20 at 01:37

1 Answers1

0

You can use touchesBegan and touchesEnded methods in UIViewController as follows:

class ViewController: UIViewController {
    var isTouching = false
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        isTouching = true
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        isTouching = false
    }
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47