简体   繁体   中英

Point not in Rect but CGRectContainsPoint says yes

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM