您的位置:首页 > 其它

关于模态弹窗点击灰色区域消失

2013-11-02 20:35 232 查看
标题是不是写的很有诗意?我自己也觉得有点儿迷糊,其实就是这样需求:模态弹出来的窗口,需要点击窗口以外的区域,也就是模态区域让这个窗口消失。一般这种场景会出现在iPad里,当你modalPresentationStyle为UIModalPresentationFormSheet时,会有这种需求。网上找了一下,这种东东还真能实现,于是想着UIAlertView是不是也可以实现呢?你猜咋地,竟然真的可以。




其实原理就是在弹框给那个view的window注册一个点击事件,然后在点击事件里判断点击区域是不是模态区域,具体代码如下:

- (IBAction)showAlert:(id)sender {

  alert = [[UIAlertView alloc] initWithTitle:@"模态测试"

                                     message:@"请点击四周的模态区域我就消失"

                                    delegate:nil

                           cancelButtonTitle:@"确定"

                           otherButtonTitles:nil];

  [alert show];

  recognizerTap = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                          action:@selector(handleTapBehind:)];

  

  [recognizerTap setNumberOfTapsRequired:1];

  recognizerTap.cancelsTouchesInView = NO; 

  [alert.window addGestureRecognizer:recognizerTap];

}

- (void)handleTapBehind:(UITapGestureRecognizer *)sender{

  if (sender.state == UIGestureRecognizerStateEnded){

    CGPoint location = [sender locationInView:nil];

    if (![alert pointInside:[alert convertPoint:location fromView:alert.window] withEvent:nil]){

      [alert.window removeGestureRecognizer:sender];

      [alert dismissWithClickedButtonIndex:0

                                  animated:YES];

    }

  }

}

看着很简单哈~

代码下载:alertTest

参考资料:
need
to dismiss the modalview form sheet controller when tap occurs on outside of the view
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: