Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift detect touch anywhere on the screen

Tags:

ios

swift

touch

I know you can detect touches using touchesBegan, touchesEnded, etc. These all work. The only thing is that they only detect the touches on the view itself, not on anything on top of that view like a text field.

My goal is to create a timeout after a certain period of inactivity. The timeout will be reset if the screen is touched, meaning someone is still using the app. It works so far, as long as they don't tap on any controls (like a label, button, textview, etc).

I could also reset the timeout when any controls are tapped, but that would require a lot more cases (different types of controls on different view controllers).

I'm looking for and end-all screen tap detection method. Any ideas?

like image 988
LuKenneth Avatar asked May 31 '16 20:05

LuKenneth


Video Answer


1 Answers

You can add this to your AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let tapGesture = UITapGestureRecognizer(target: self, action: nil)
        tapGesture.delegate = self
        window?.addGestureRecognizer(tapGesture)

        return true
}

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        // User tapped on screen, do whatever you want to do here.

        return false
}

And also make your AppDelegate conform to UIGestureRecognizerDelegate protocol.

like image 69
Nati Avatar answered Sep 19 '22 14:09

Nati