简体   繁体   English

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

[英]How do I handle event when user touch up outside the UIView?

I have a custom popup menu in my iOS application. 我的iOS应用程序中有一个自定义弹出菜单。 It is UIView with buttons on it. UIView上有按钮。 How do I handle event when user touch up outside this view? 当用户在此视图外部进行修饰时,如何处理事件? I want to hide menu at this moment. 我想暂时隐藏菜单。

You should create a custom UIButton that takes up the whole screen. 您应该创建一个占据整个屏幕的自定义UIButton Then add your subview on top of that button. 然后在该按钮的顶部添加子视图。 Then when the user taps outside of the subview they will be tapping the button. 然后,当用户点击子视图之外时,他们将点击按钮。

For example, make the button like this: 例如,按下这样的按钮:

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

(where yourhidemethod: is the name of the method that removes your subview.) Then add your subview on top of it. (其中yourhidemethod:是删除子视图的方法的名称。)然后在其上添加子视图。


Update: It looks like you're wanting to know how to detect where touches are in a view. 更新:您似乎想知道如何检测视图中的触摸位置。 Here's what you do: 这是你做的:

-(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 
}

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

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

It sounds like you'd be better served by deriving your menu from UIControl rather than UIView. 听起来你可以通过从UIControl而不是UIView获取菜单来获得更好的服务。 That would simplify the touch handling, and all you'd have to do in this case would be to set a target and action for UIControlEventTouchUpOutside. 这将简化触摸处理,在这种情况下您需要做的就是为UIControlEventTouchUpOutside设置目标和操作。 The target could be the menu itself, and the action would hide or dismiss the menu. 目标可以是菜单本身,操作将隐藏或关闭菜单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM