iOS之UIAlertView点击窗口之外区域关闭

96
念念不忘一个丫头的容
2017.06.09 15:34* 字数 27

弹出一个UIAlertView,然后点击窗口之外的区域来关闭UIALertView,代码如下:

- (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;   
  [[UIApplication sharedApplication].keyWindow 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];  
    }  
  }  
}  
日记本
Web note ad 1