当用户在UIView之外触摸时,如何处理事件?

问题描述:

我在我的iOS应用程序中有一个自定义的弹出式菜单。它是带有按钮的UIView。当用户在此视图之外触摸时,如何处理事件?此时我想隐藏菜单。当用户在UIView之外触摸时,如何处理事件?

您应该创建占用整个屏幕的自定义UIButton。然后在你的按钮上添加你的子视图。然后,当用户在子视图之外轻敲时,他们将点击按钮。

例如,使按钮这样的:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button addTarget:self action:@selector(yourhidemethod:) forControlEvents:UIControlEventTouchUpInside]; 
[button setTitle:@"" forState:UIControlStateNormal]; 
button.frame = self.view.frame; 
[self.view addSubview:button]; 

(其中yourhidemethod:是消除你的子视图的方法的名称),然后加在它上面的子视图。


更新:它看起来像你想知道如何检测触摸在视图中的位置。以下是你的工作:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self]; //location is relative to the current view 
    // do something with the touched point 
} 
+0

谢谢!它的工作令人敬畏。 – Raja 2017-03-01 09:31:29

一个想法是有一个不可见的视图(uicontrol),它与屏幕一样大,然后保存这个自定义弹出窗口。

将它放在全屏幕透明视图中并处理触摸。

+0

哦,thx。但我不知道如何处理视线。有人能帮助我吗? – 2011-03-10 17:36:04

+0

那么你可以得到你想要的,而无需手动触摸处理。在该全屏视图中,您还可以添加一个由'[UIButton buttonWithType:UIButtonTypeCustom]'制作的UIButton实例。之后,所有你必须做它来添加你的控制器(或任何你用来处理这个菜单)作为这个按钮的目标,像'[button addTarget:self action:@selector(transparenViewTapped :) forControlEvents:UIControlEventTouchUpInside]'。 – hoha 2011-03-10 17:41:10

+0

我已经询问了有关手动触摸操作的情况。你能给我一些信息或链接到关于这个问题的文档吗? – 2011-03-10 17:43:23

听起来你会更好地从UIControl而不是UIView获取菜单。这将简化触摸处理,在这种情况下,您只需为UIControlEventTouchUpOutside设置目标和操作即可。目标可以是菜单本身,并且该操作可以隐藏或关闭菜单。