How to know that whether a tap is inside a view or outside in swift

Joe picture Joe · Jan 16, 2017 · Viewed 9.6k times · Source

I'm try to develop code part, to check whether mine tap is inside a view or outside a view, i tried with pointInside method. If A is main View Controller and B is subView of A, How can i get to know that user tapped inside B.

Answer

Code Different picture Code Different · Jan 16, 2017

Apple explains it very well in Responder Chain. You can add the following function to your view controller:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let firstTouch = touches.first {
        let hitView = self.view.hitTest(firstTouch.location(in: self.view), with: event)

        if hitView === viewB {
            print("touch is inside")
        } else {
            print("touch is outside")
        }
    }
}