HitTest: withEvent: Doesn't work

I am creating an application where I have a background view and I have six UIImageView as subzones. I have a UITapGestureRecognizer to see when one of the UIImageView , and the handleTap method below is what the gesture recognizer calls. However, when I run this, hitTest:withEvent: always returns a background view even when clicking on one of the images. Does this have anything to do with the event when I call hitTest?

thanks

 - (void) handleTap: (UITapGestureRecognizer *) sender { if (sender.state == UIGestureRecognizerStateEnded) { CGPoint location = [sender locationInView: sender.view]; UIView * viewHit = [sender.view hitTest:location withEvent:NULL]; NSLog(@"%@", [viewHit class]); if (viewHit == sender.view) {} else if ([viewHit isKindOfClass:[UIImageView class]]) { [self imageViewTapped: viewHit]; NSLog(@"ImageViewTapped!"); } } } 
+6
source share
2 answers

UIImageView is configured by default to not log user interaction.

From the UIImageView documentation:

New image viewers are configured to ignore custom events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled - YES property after initializing the object.

So, immediately after initializing your views, you should:

 view.userInteractionEnabled = YES; 

This will enable interaction again, and you will be able to record touch events.

+12
source

Your approach will be written there (one GR on the containing view), which will work, but it will cause our brain to damage the correct coordinate systems, which is definitely a problem in the hosted code.

The best answer is to attach N gesture recognizers to each of the UIImageViews. They can have the same target and use the same handleTap: method. HandleTap: can get a view without looking for any geometry like this:

 UIImageView *viewHit = (UIImageView *)sender.view; 
+1
source

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


All Articles