Comparing a UITouch location to UIImageView rectangle

烈酒焚心 提交于 2019-12-05 06:20:53

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.

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.

UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:self];
if ([touch view]==view) {
view.center=location;
}

write it in the touch moved event. thanx

Remember that when you're asking a touch for locationInView:, you're getting out a point relative to that view's frame. So, assuming the code snippet you gave was contained in a subclass of UIViewController you should be asking for

CGPoint touchLocation = [touch locationInView:self.view];

Which will give you a point relative to your view. The reason you want a point relative to your current view is because the frame of your image view is also relative to its parent view - the same view. So now it should work.

 if (CGRectContainsPoint(myImageView.frame, touchLocation)) {
    NSLog(@"Tapped image view");
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!