当进行ios开发的时候 会要到 弹出视图方法 有时会有这样的需求 点击空白处关闭视图
弹出视图
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0);
关闭被弹出视图
- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^)(void))completion NS_AVAILABLE_IOS(5_0);
以下方法是通过给window添加手势UITapGestureRecognizer 判断点击位置 来实现 点击空白处关闭视图
弹出视图就不用说了 下面是 在被弹出视图中进行关闭(谁污染谁治理原则)
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handletapPressGesture:)];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
[app.window addGestureRecognizer:tapGesture];
}
-(void)handletapPressGesture:(UITapGestureRecognizer*)sender{
CGPoint point = [sender locationInView:self.view];
if (point.x<self.view.frame.origin.x || point.x >self.view.frame.origin.x+self.view.frame.size.width) {
[self dismissViewControllerAnimated:YES
completion:^{
//一定要移除手势 否则下次 没有子视图的时候 点击 会崩溃拉
AppDelegate *app = [[UIApplication sharedApplication] delegate];
[app.window removeGestureRecognizer:sender];
}];
}
}