Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a UITouch location to UIImageView rectangle

I have the following code to determine if a touch is within an image view in my table cell. However, it doesn't work. I compared the two with CGRectContainsPoint however, it doesn't work. Here is the code:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event    
{
     // Declare the touch and get it's location

     UITouch *touch = [touches anyObject];

     CGPoint touchLocation = [touch locationInView:self];

     if (CGRectContainsPoint(myImageView.frame, touchLocation))
     {
        NSLog(@"Tapped image view");
     }    
}

Thanks for the help!

like image 867
skylerl Avatar asked Feb 08 '10 12:02

skylerl


2 Answers

However, it doesn't work.

Please be more specific.

 UITouch *touch = [touches anyObject];

Why not examine every touch, and not simply a random* pick of them?

*The documentation for anyObject says that you are not guaranteed which one it will give you. You are not even guaranteed that it will be random; it could be the same object every time. Murphy's Law says that, whether it is random or not, it will be the wrong one.

 CGPoint touchLocation = [touch locationInView:self];
 if (CGRectContainsPoint(myImageView.frame, touchLocation))

Your frame is in your superview's co-ordinate system; [touch locationInView:self] returns the touch point in your co-ordinate system. You want to test within bounds, which is in your co-ordinate system. The documentation explains the difference.

like image 171
Peter Hosey Avatar answered Sep 28 '22 21:09

Peter Hosey


The problem is that you need to be calling [touch locationInView:myImageView] to get the point in the image views coordinate system. Then do your check to see if it's within the frame.

like image 35
bstahlhood Avatar answered Sep 28 '22 19:09

bstahlhood