将UITouch位置与UIImageView矩形进行比较

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个回答

26

然而,它没有起作用。

请更具体一些。

 UITouch *touch = [touches anyObject];
为什么不检查每一个触摸事件,而不是随机选择其中一个呢?
* anyObject文档说,不能保证返回的是哪一个对象。你甚至不保证它会是随机的;它可能每次都是同一个对象。无论是否随机,根据墨菲定律,它都会是错误的。
 CGPoint touchLocation = [touch locationInView:self];
 if (CGRectContainsPoint(myImageView.frame, touchLocation))
您的frame在您的父视图坐标系中;[touch locationInView:self]会返回触摸点在您的坐标系中的位置。 您希望测试bounds,它在您的坐标系中。 文档解释了这两者的区别。

д»…еҪ“myImageViewжҳҜselfзҡ„зӣҙжҺҘеӯҗи§Ҷеӣҫж—¶пјҢжү©еұ•CGPoint touchLocation = [touch locationInView:self]; if (CGRectContainsPoint(myImageView.frame, touchLocation))жүҚжңүж•ҲгҖӮ - João Portela
1
扩展Joao的评论,您可以使用CGRect frameRelativeToView = [myImageView convertRect:myImageView.bounds toView:self]获取子视图相对于父视图(或任何视图)的框架。 - chazzwozzer

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

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


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

0
请记住,当您请求locationInView:的触摸时,您会得到相对于该视图框架的点。因此,假设您提供的代码片段包含在UIViewController的子类中,则应该请求。
CGPoint touchLocation = [touch locationInView:self.view];

这将为您提供相对于您的视图的点。您希望相对于当前视图获得一个点的原因是因为图像视图的框架也相对于其父视图 - 同一视图。所以现在应该可以工作了。

 if (CGRectContainsPoint(myImageView.frame, touchLocation)) {
    NSLog(@"Tapped image view");
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接