How to detect a tap gesture in subviews

26,202

Solution 1

You can grab the point of the tap off the gesture recognizer when your handler method is called respective to any view you wish using -locationInView:. Then, use the following method on UIView: - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event to get a reference to the actual sub view that was tapped remembering that the point you pass in is in the same coordinate space as the view.

Some code to get you started:

CGPoint point = [tapGestureRecognizer locationInView:parentView];
UIView *tappedView = [parentView hitTest:point withEvent:nil];

For hit testing to work the view needs to have the userInteractionEnabled property set to YES. Many views, such as UILabels have this set to NO by default. So prior to the above:

self.subviewOfInterest.userInteractionEnabled = YES;

Solution 2

maybe you should set as: subviews.userInteractionEnabled = YES; good luck!

Share:
26,202
Fitzy
Author by

Fitzy

Donate: Bitcoin: 18YFRUwQne2cPivXSGWL7AffoCK2qR71Bi Ethereum: 0xAD66D5F9BC59924152361ce4B58aA8fa63A9a9Ae

Updated on August 29, 2020

Comments

  • Fitzy
    Fitzy over 3 years

    Quick question: how do i detect if a tap gesture recognizer is within a subview of the view it is added to? Eg. if i click on an object such as a square that has been added as a subview to a background which a tap gesture recognizer has been added to, how do I detect that it has been tapped?