首页 > 开发 > iOS > 正文

怎么让 UIAlertControllerStyleAlert 在用户点击空白处时自动隐藏?

2017-09-08 13:45:01  来源:网友分享

使用 UIAlertController 弹出对话框时,想支持用户点击空白处能自动隐藏对话框;

按照 UIAlertControllerStyleActionSheet 点击空白处不隐藏问题 设置 UIAlertActionStyleCancel 时,需要 StyleUIAlertControllerStyleActionSheet 能生效,当设置为 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];}