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

问题描述 投票:4回答:2

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

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

@interface SomeMasterViewController : UITableViewController <clip>

<clip>

@property (strong, nonatomic) UIImageView *someImageView;

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

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

  1. 注册UITapGestureRecognizer以获取应用程序中可能发生的所有触摸事件
  2. UITapGestureRecognizer应将其cancelsTouchesInView和delaysTouchesBegan以及delayedTouchesEnded设置为NO。
  3. 将这些触摸事件与someImageView进行比较(如何使用UIView hitTest:withEvent?)

更新:我正在使用主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>>
ios uigesturerecognizer uitouch
2个回答
4
投票

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

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


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;

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

在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];

      }
}
© www.soinside.com 2019 - 2024. All rights reserved.