Detect any tap outside the current view

前端 未结 2 1643
北海茫月
北海茫月 2021-01-04 05:49

Is there a way to detect any tap outside the current view? I unsuccessfully tried to implement something with the hitTest method but I am not sure to understand it well.

2条回答
  •  死守一世寂寞
    2021-01-04 06:18

    You can use UIGestureRecognizerDelegate protocol

        extension YourViewController: UIGestureRecognizerDelegate {
    
          func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                                 shouldReceive touch: UITouch) -> Bool {
            return (touch.view === self.view)
          } 
        }
    

    This will only returns "true" when the touch was on the background view but "false" if it was inside the your View.

    Note : The identity operator === to compare touch.view with self.view. You want to know whether both variables refer to the same object.

    And in viewDidLoad() you will create the gestureRecognizer and set delegate.

    let gestureRecognizer = UITapGestureRecognizer(target: self,action: #selector(yourActionMethod))
    gestureRecognizer.cancelsTouchesInView = false
    gestureRecognizer.delegate = self
    view.addGestureRecognizer(gestureRecognizer)
    

提交回复
热议问题