使用 UIAlertController 弹出对话框时,想支持用户点击空白处能自动隐藏对话框;
按照 UIAlertControllerStyleActionSheet 点击空白处不隐藏问题 设置 UIAlertActionStyleCancel
时,需要 Style 为 UIAlertControllerStyleActionSheet 能生效,当设置为 UIAlertControllerStyleAlert
并没有效果;
请问有办法实现此效果吗??
解决方案
原理
UIAlertController
是创建一个window, 白色部分为UIAlertController的View, 然后把window加在[UIApplication sharedApplication].windows
上.
思路
在点击window, 释放(dismiss)UIAlertController, 执行dismiss会调用类型为style:UIAlertActionStyleCancel或者UIAlertActionStyleDestructive的handler闭包
- (void)showAlert{ UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert]; [alertVC addAction:[UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:nil]]; [alertVC addAction:[UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { NSLog(@"NO"); }]]; _alertVC = alertVC; [self presentViewController:alertVC animated:YES completion:nil]; // 增加点击事件 UIWindow *alertWindow = (UIWindow *)[UIApplication sharedApplication].windows.lastObject; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAlert)]; [alertWindow addGestureRecognizer:tap];}- (void)hideAlert{ UIWindow *alertWindow = (UIWindow *)[UIApplication sharedApplication].windows.lastObject; [alertWindow removeGestureRecognizer:tap]; [_alertVC dismissViewControllerAnimated:YES completion:nil];}