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

标题是不是写的很有诗意?我自己也觉得有点儿迷糊,其实就是这样需求:模态弹出来的窗口,需要点击窗口以外的区域,也就是模态区域让这个窗口消失。一般这种场景会出现在iPad里,当你modalPresentationStyle为UIModalPresentationFormSheet时,会有这种需求。网上找了一下,这种东东还真能实现,于是想着UIAlertView是不是也可以实现呢?你猜咋地,竟然真的可以。
iOS Simulator Screen shot 2012-12-31 PM3.43.10
其实原理就是在弹框给那个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

    分享到:

About rainbird

IOS攻城狮
This entry was posted in IOS开发, object-c, xCode and tagged , , , , , , , , . Bookmark the permalink.

发表评论