Reputation: 1394
I have a UIImageView
whose 'View Mode' is set to 'Aspect Fit' in Interface Builder.I want to add gesture recognizer to only my image inside of the UIImageView
.To clarify what i say:
I have a UIImageView
whose bounds.size.width = 100;
and bounds.size.height = 100;
and I have a UIImage
whose size is 100x50. So, when I add my UIImage
to my UIImageView
there exists some spaces of 25 from top and 25 from bottom. But I don't want to recognize user's tap when he/she taps on these spaces. I just want to know when user tapped on UIImage
.
How can I do that?
Upvotes: 0
Views: 611
Reputation: 762
As UIImage
extends from NSObject
you can not add UITapGestureRecognizer
to it, you have to add gesture to the UIImageView
itself. Then in any of the UIGestureRecognizer
delegate methods:
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;
or
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
get touch's location in UIImageView
. Then by using CGPoint location = [_gesture locationInView:yourImageView]
get the touched point, now get the image's frame using this link. Now check if the point is in Image's frame or not by using:
bool CGRectContainsPoint ( CGRect rect, CGPoint point );
This might help you.
Upvotes: 1
Reputation: 9687
You have to add the gesture recognizer to the imageView. What you can do it use the gesture recognize delegate methods:
- gestureRecognizerShouldBegin:
//OR
- gestureRecognizer:shouldReceiveTouch:
You can then figure out where the user tapped in the imageView and compute if the touch landed inside the image in the imageView or outside the image.
You can do this using using the following:
CGPoint tapPoint = [gestureRecognizer locationInView:imageView];
// use tap point to compute if it lands inside the image.
Upvotes: 1