Kashif
Kashif

Reputation: 4632

Detect when a touch begins anywhere on screen even on a UIButton

I am looking for a simple way to detect when the user starts to touch the screen regardless of whether they are touching on a UIButton or elsewhere on the screen.

If I use touchesBegan(... on my ViewController, it does not detect touches on controls like UIButtons.

There is UITapGesturReconizer on ViewController but that would fire only when the tap has completed. I am looking to detect when any touch begins.

Upvotes: 0

Views: 561

Answers (1)

krbiz
krbiz

Reputation: 393

Use a UILongPressGestureRecognizer and set its minimumPressDuration to 0. It will act like a touch down during the UIGestureRecognizerStateBegan state.

func setupTap() {
    let touchDown = UILongPressGestureRecognizer(target:self, action: #selector(didTouchDown))
    touchDown.minimumPressDuration = 0
    view.addGestureRecognizer(touchDown)
}

@objc func didTouchDown(gesture: UILongPressGestureRecognizer) {
    if gesture.state == .began {
        doSomething()
    }
}

Upvotes: 1

Related Questions