【问题标题】:Comparing a UITouch location to UIImageView rectangle将 UITouch 位置与 UIImageView 矩形进行比较
【发布时间】:2010-02-08 12:01:00
【问题描述】:

我有以下代码来确定触摸是否在我的表格单元格的图像视图中。但是,它不起作用。我将两者与 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");
     }    
}

感谢您的帮助!

【问题讨论】:

    标签: iphone objective-c cocoa-touch uikit uitouch


    【解决方案1】:

    但是,它不起作用。

    请更具体。

     UITouch *touch = [touches anyObject];
    

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

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

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

    您的frame 在您的superview 的坐标系中; [touch locationInView:self] 返回你的坐标系中的接触点。您想在您的坐标系中的bounds 内进行测试。 The documentation explains the difference.

    【讨论】:

    • 扩展:CGPoint touchLocation = [touch locationInView:self]; if (CGRectContainsPoint(myImageView.frame, touchLocation)) 仅在 myImageViewself 的直接子视图时才有效
    • 扩展 Joao 的评论,您可以使用 CGRect frameRelativeToView = [myImageView convertRect:myImageView.bounds toView:self] 获得相对于父视图(或任何视图)的子视图框架
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      UITouch *touch = [[event allTouches] anyObject];
      CGPoint location = [touch locationInView:self];
      if ([touch view]==view) {
      view.center=location;
      }
      

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

      【讨论】:

        【解决方案4】:

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

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-27
          • 1970-01-01
          相关资源
          最近更新 更多