6

我有以下代码来确定触摸是否在我的表格单元格的图像视图中。但是,它不起作用。我将两者与 CGRectContainsPoint 进行了比较,但是它不起作用。这是代码:

-(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");
     }    
}

谢谢您的帮助!

4

4 回答 4

26

但是,它不起作用。

请更具体。

 UITouch *touch = [touches anyObject];

为什么不检查每一次触摸,而不是简单地*挑选它们?

*的文档anyObject说你不能保证它会给你哪一个。你甚至不能保证它是随机的;每次都可能是同一个对象。墨菲定律说,无论是否随机,都会是错误的。

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

frame在你的superview的坐标系中;[touch locationInView:self]返回坐标系中的接触点。您想bounds在您的坐标系中进行测试。该文档解释了差异。

于 2010-02-08T12:32:22.847 回答
1

问题是您需要调用 [touch locationInView:myImageView] 来获取图像视图坐标系中的点。然后检查它是否在框架内。

于 2010-02-20T02:34:49.277 回答
1
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:self];
if ([touch view]==view) {
view.center=location;
}

把它写在触摸移动事件中。谢谢

于 2011-10-29T11:21:58.547 回答
0

请记住,当您要求触摸 locationInView: 时,您将得到一个相对于该视图框架的点。因此,假设您提供的代码片段包含在 UIViewController 的子类中,您应该要求

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

这会给你一个相对于你的观点的观点。您想要一个相对于当前视图的点的原因是因为您的图像视图的框架也相对于它的父视图 - 相同的视图。所以现在它应该可以工作了。

 if (CGRectContainsPoint(myImageView.frame, touchLocation)) {
    NSLog(@"Tapped image view");
 }
于 2010-09-14T03:30:30.540 回答