Hit test helps us to understand if a view can be interactive with user.
func hitTest(_ point: CGPoint,with event: UIEvent? ) -> UIView?
When the touch event is performed by the user, the system calls this function to trigger the touch or gesture recognizer an returns the frontmost view interacted with.
If we have multiple subviews in a view, how to perform a hit test on views?
Let’s say we want to interact with the purple one and not the green one.
isUserInteractionEnabled = false
this method cannot be used for green view because then purple view will be affected by it. So the solution is, overriding hit test on foremost view (green view) like this:
override func hitTest(_ point: CGPoint,with event: UIEvent? ) -> UIView?{ let view = super.hitTest(point,with: event) if view = self{ return nil //if green view, do nothing } return view //if purple view, return it to do something
}