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.
Asked
Active
Viewed 1.4k times
2 Answers
30
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")
}
}
}

Code Different
- 90,614
- 16
- 144
- 163
-
missing argument for parameter 'with' in call. i didn't get it. – Joe Jan 16 '17 at 11:16
-
1Do we need to set some delegate? Since it is not getting fired. – Jayprakash Dubey Jul 17 '17 at 10:17
-
if hitView != viewB { print("is outside the view") } maybe would help someone) – J A S K I E R Dec 19 '20 at 14:15
17
In the tapGestureRecognizer
callback you can use the method tapGesture.location(in: A)
in order to fetch the x, y position of the A referral system. Then you can use B.frame.contains(location)
.
If true, then the tap is in B.
Depending on what you want to do there are simpler approaches to the problem. For example, you could add the gestureRecognizer
to B instead of A, if you are interested just in touches inside B.
I don't know which are exactly your needs. With more info I could give you better advices.

Hiren Dhamecha
- 658
- 5
- 15

Giuseppe Lanza
- 3,519
- 1
- 18
- 40
-
If with this methods use: convertPoint: fromView: it would be really useful. – Neph Muw Mar 22 '19 at 10:29