如何检测在UIImageView外部点击的人

时间:2012-04-06 00:02:21

标签: ios uigesturerecognizer uitouch

我有一个UIImageView作为子视图添加。按下按钮时显示。

当有人在应用程序的任何部分点击UIImageView之外时,我希望UIImageView消失。

@interface SomeMasterViewController : UITableViewController <clip>

<clip>

@property (strong, nonatomic) UIImageView *someImageView;

stackoverflow和Apple的文档中有一些提示听起来像我需要的。

但是,我想在这里查看我的方法。我的理解是代码需要

  1. 注册UITapGestureRecognizer以获取应用程序中可能发生的所有触摸事件

  2. UITapGestureRecognizer应该有cancelsTouchesInView和 delaysTouchesBegan和delaysTouchesEnded设置为NO。

  3. 将这些触摸事件与someImageView进行比较(如何使用UIView hitTest:withEvent?)

  4. 更新:我正在使用主UIWindow注册UITapGestureRecognizer。

    最终未解决的部分

    我有一个UTapGestureRecognizer会调用的handleTap :( UITapGestureRecognizer *)。如何获取给定的UITapGestureRecognizer并查看水龙头是否落在UIImageView之外?识别器的locationInView看起来很有希望,但我没有得到我期望的结果。当我点击它时我希望看到某个UIImageView,当我点击另一个点时看不到UIImageView。我觉得 locationInView 方法使用错误。

    这是我对locationInView方法的调用:

    - (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer
    {
        if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
            NSLog(@"handleTap NOT given UIGestureRecognizerStateEnded so nothing more to do");
            return;        
        }
    
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        CGPoint point = [gestureRecognizer locationInView:mainWindow];
        NSLog(@"point x,y computed as the location in a given view is %f %f", point.x, point.y);
    
        UIView *touchedView = [mainWindow hitTest:point withEvent:nil];
        NSLog(@"touchedView = %@", touchedView); 
    }
    

    我得到以下输出:

    <clip>point x,y computed as the location in a given view is 0.000000 0.000000
    
    <clip>touchedView = <UIWindow: 0x8c4e530; frame = (0 0; 768 1024); opaque = NO; autoresize = RM+BM; layer = <UIWindowLayer: 0x8c4c940>>
    

2 个答案:

答案 0 :(得分:4)

你可以说[event touchesForView:<image view>]。如果返回空数组,则关闭图像视图。在表格视图控制器的touchesBegan:withEvent:中执行此操作,并确保调用[super touchesBegan:touches withEvent:event]或您的表格视图将完全停止工作。您甚至可能不需要实现touchesEnded:/Cancelled:...touchesMoved:...

UITapGestureRecognizer在这种情况下看起来似乎有些过分。

答案 1 :(得分:2)

您可以使用触控功能执行此操作:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

当用户首先触摸屏幕时,会调用touchBegan函数。

in touchBegan:

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    CGPoint pt = [[touches anyObject] locationInView:self]; 
}

所以你有点用户触摸。然后你必须发现该点在你的UIImageView中。

但是如果你可以为你的UIImageViews提供标签。这将非常简单。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

      UITouch *touch = [touches anyObject ];

      if( yourImageView.tag==[touch view].tag){

         [[self.view viewWithTag:yourImageView.tag] removeFromSuperView];
         [yourImageView release];

      }
}