views:

1599

answers:

2

If I have a UIImageView and want to know if a user has tapped the image. In touchesBegan, I do the following but always end up in the first conditional. The window is in portrait mode and the image is at the bottom. I can tap in the upper right of the window and still go into the first condition, which seems very incorrect.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:touch.view];

if(CGRectContainsPoint(myimage.frame, location) == 0){
//always end up here
}
else
{ //user didn't tap inside image}

and the values are:

location: x=303,y=102
frame: origin=(x=210,y=394) size=(width=90, height=15)

Any suggestions?

+3  A: 

Your logic is simply inverted. The CGRectContainsPoint() method returns bool, i.e. true for "yes". True is not equal to 0.

unwind
0 is always false in C. It's almost never true in any computing context (I can't think of any language that uses 0 as True, though there might be one).
Chuck
@Chuck: Sure, but there are cases where 0 does indicate "(sort of) success" (like strcmp()), which is why I wrote it that way.
unwind
+2  A: 

First, you get the touch with:

UITouch *touch = [[event allTouches] anyObject];

Next, you want to be checking for the locationInView relative to your image view.

CGPoint location = [touch locationInView:self]; // or possibly myimage instead of self.

Next, CGRectContainsPoint returns a boolean, so comparing it to 0 is very odd. It should be:

if ( CGRectContainsPoint( myimage.frame, location ) ) {
   // inside
} else {
   // outside
}

But if self is not myimage then the myimage view may be getting the touch instead of you - its not clear from your question what object self is it is is not a subclass of the UIImageView in question.

Peter N Lewis
Not according to the docs: developer.apple.com/documentation/graphicsimaging/… - "Returns 1 if the specified point is located within the specified rectangle; otherwise, 0." Using the code as above with self.view works since it's a UIViewController. Thanks.
4thSpace
4thSpace: Exactly. It returns 0 (and, therefore, the equality is true) because the point is outside the rectangle. If the point had been inside the rectangle, CGRectContainsPoint would have returned true (1), and the equality would have been false.
Peter Hosey