Point is not in Rect, but CGRectContainsPoint says yes

If I have a UIImageView and want to find out if the user clicked an image. In touchBegan, I do the following, but always find myself in the first conditional. The window is in portrait mode, and the image is at the bottom. I can click in the upper right corner of the window and still go to the first condition, which seems very wrong.

- (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 values:

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

Any suggestions?

+4
source share
2 answers

First, you get contact with:

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

Next, you want to check the location of the InView relative to your image.

 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 I'm not myimage, then the myimage view can get a touch for you - it is not clear from your question what the object itself is, it is not a subclass of the UIImageView in question.

+19
source

Your logic is just inverted. The CGRectContainsPoint() method returns bool, i.e. True for yes. True is not 0.

+4
source

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


All Articles