Swift detect touch anywhere on the screen

前端 未结 2 931
抹茶落季
抹茶落季 2021-02-07 11:01

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 t

相关标签:
2条回答
  • 2021-02-07 11:47

    Drag and drop UITapGestureRecognizer, make sure the whole view is selected. It will be added on the top line of your view controller, then create an Action for it.

    If you want to make sure that any of the buttons is not pressed, once the period of inactivity completed, add another view (can be transparent or just a bit darker) on it and connect the UITapGestureRecognizer to it. Once tapped, release the added view and resume activity.

    0 讨论(0)
  • 2021-02-07 11:55

    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.

    0 讨论(0)
提交回复
热议问题