最新消息:iOS编程开发交流群(6906921) ,Mac.Cocoa开发交流群(7758675) 欢迎iOS/macOS开发编程爱好及学习者加入!

iOS点击空白处关闭presentViewController出来的view

iOS 天狐 27341浏览 0评论

当进行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];
                                 }];
    }

}

 

转载请注明:天狐博客 » iOS点击空白处关闭presentViewController出来的view

微信 OR 支付宝 扫描二维码
为天狐 打赏
非常感谢你的支持,哥会继续努力!
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址