Detect any touch outside the current view

Is there a way to detect any access outside the current view? I tried unsuccessfully to implement something using the hitTest method, but I'm not sure to figure it out.

+4
source share
2 answers

What you need to do, in touchhesBegan you need to get the first touch object from the set of touchs , and you need to check the location of this touch in (inside of which you want to detect the touch).

After you get the touch location in the view, you need to check if there is a currentView (the view you need to check if the input was inside or outside).

If the currentView frame contains the location of the touch, this means that the touch occurred inside the view, otherwise outside it.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        guard let location = touch?.location(in: self.view) else { return }
        if !currentView.frame.contains(location) {
            print("Tapped outside the view")
        }else {
            print("Tapped inside the view")
        }
    }

Hope this helps!

+5
source

You can use the UIGestureRecognizerDelegate protocol

    extension YourViewController: UIGestureRecognizerDelegate {

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

This only returns β€œtrue” if the touch was in the background, but β€œfalse” if it was inside your view.

Note. Identity operator === for comparing touch.view with self.view. You want to know if both variables refer to the same object.

viewDidLoad() gestureRecognizer .

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

Source: https://habr.com/ru/post/1675162/


All Articles