您的位置:首页 > 移动开发 > IOS开发

模态弹窗,点击黑色半透明区域消失

2014-04-04 15:48 1631 查看
点击黑色半透明区域让模态弹窗消失,很简单,给模态窗口的加一个手势就行了,我的模态窗口是一个viewController,大家可以灵活变通,道理都一样。

在viewDidAppear(viewWillAppear应该也行,我没试,不过不能在viewDidLoad中)中,给window加一个tap手势监听。注意一定是给window加,因为self.view只是模态窗口的那部分,不包括黑色半透明区域。我将recognizerTap定义成全局的了,因为别的方法中还会用到这个变量。

recognizerTap = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                            action:@selector(handleTapBehind:)];

    

[recognizerTap setNumberOfTapsRequired:1];

recognizerTap.cancelsTouchesInView = NO;

[self.view.window addGestureRecognizer:recognizerTap];

handleTapBehind方法如下:

- (void)handleTapBehind:(UITapGestureRecognizer *)sender

{

    if (sender.state == UIGestureRecognizerStateEnded)

    {

        CGPoint location = [sender locationInView:nil];

        if(self.navigationController)

        {

            if (![self.view pointInside:[self.view convertPoint:location fromView:self.view.window] withEvent:nil])

            {

                [self dismissViewControllerAnimated:YES completion:nil];

            }

        }

    }

}

这个方法中判断用户点击的点是在self.view中,还是黑色半透明区域,如果是在黑色半透明区域,则消失。

这还没有结束,一定要记得在窗口消失的时候remove 注册的手势tap 手势监听,在viewWillDisappear方法中,加上:

[self.view.window removeGestureRecognizer:recognizerTap];

至此,结束!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息