Detecting touch event outside certain UIView

ban*_*ndw 4 iphone uiview ios

In my app, to click a button will pop up a UIView, now I want to click anywhere outside of the UIView to dismiss the UIView.
I have tried adding a large transparent button under the UIView, invoke the button action to dismiss the UIView, but the button can't be expanded to Fullscreen because of the top navigationbar and bottom tabbar
Is any other way to achieve?

Luc*_*rdo 8

一个巨人,UIButton它不是解决你的问题的好方法.你可以简单地使用UIGestureRecognizer它.

您可以像这样分配一个:

UITapGestureRecognizer *tapImageRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(dismissPopUp)];
Run Code Online (Sandbox Code Playgroud)

然后,只需将手势添加到要响应所选选择器的视图中.

[self.view addGestureRecognizer:tapImageRecognizer];
Run Code Online (Sandbox Code Playgroud)

可能还有其他人

[self.navBar addGestureRecognizer:tapImageRecognizer];
//etc
Run Code Online (Sandbox Code Playgroud)

只是不要忘记实现手势识别器使用的方法

-(void)dismissPopUp
{
   //your dimiss code here
}
Run Code Online (Sandbox Code Playgroud)

  • 迟到但您必须使用removeGestureRecognizer删除手势识别器,如[self.view removeGestureRecognizer:(UIGestureRecognizer*)].当然,您必须保持对手势识别器的引用. (2认同)